当前位置:网站首页>Promise (三) async/await
Promise (三) async/await
2022-08-05 05:47:00 【要不要买菜啊】
async 函数
async 函数是使用async关键字声明的函数。 async 函数是AsyncFunction构造函数的实例, 并且其中允许使用await关键字。async和await关键字让我们可以用一种更简洁的方式写出基于Promise的异步行为,而无需刻意地链式调用promise。
特点
async function main(){
//1. 如果返回值是一个非Promise类型的数据,会返回一个resolved的promise对象,值为该数据
// return 521;
//2. 如果返回的是一个Promise对象
return new Promise((resolve, reject) => {
resolve('OK');
// reject('Error');
});
//3. 抛出异常
// throw "Oh NO";
}
let result = main();
console.log(result);await 表达式
async function main(){
let p = new Promise((resolve, reject) => {
resolve('OK');
// reject('Error');
})
//1. 右侧为promise的情况
// let res = await p;
//2. 右侧为其他类型的数据
let res2 = await 20;
// console.log(res2); // 20
//3. 如果promise是失败的状态
// try{
// // let res3 = await p;
// }catch(e){
// console.log(e);
// }
}
main();注意
async与await结合
const fs = require('fs');
const util = require('util');
// 将 API 转为promise形式的函数
const mineReadFile = util.promisify(fs.readFile);
//回调函数的方式
// fs.readFile('./resource/1.html', (err, data1) => {
// if(err) throw err;
// fs.readFile('./resource/2.html', (err, data2) => {
// if(err) throw err;
// fs.readFile('./resource/3.html', (err, data3) => {
// if(err) throw err;
// console.log(data1 + data2 + data3);
// });
// });
// });
//async 与 await
// 出错也不需要每一层都去判断,使用try...catch即可
async function main(){
try{
//读取第一个文件的内容
let data1 = await mineReadFile('./resource/1.html');
let data2 = await mineReadFile('./resource/2.html');
let data3 = await mineReadFile('./resource/3.html');
console.log(data1 + data2 + data3);
}catch(e){
console.log(e.code);
}
}
main();边栏推荐
猜你喜欢
随机推荐
《PyTorch深度学习实践》第十一课(卷积神经网络CNN高级版)
浮点数基础知识
HelloWorld
After docker is deployed, mysql cannot connect
错误记录集锦(遇到则记下)
scikit-image image processing notes
NB-IOT智能云家具项目系列实站
自营商城提高用户留存小技巧,商城对接小游戏分享
【FAQ】What is Canon CCAPI
Writing OpenCV in VSCode
字体样式及其分类
淘宝宝贝页面制作
LaTeX uses frame to make PPT pictures without labels
The 25 best free games on mobile in 2020
uniapp打包次数限制怎么办?只需两步就能解决
#Sealos#使用工具部署kubernetesV1.24.0
Error correction notes for the book Image Processing, Analysis and Machine Vision
numpy.random usage documentation
小程序input框不允许输入负数
2022杭电多校六 1006-Maex (树形DP)









