当前位置:网站首页>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();边栏推荐
猜你喜欢

多行文本省略

MySQL的主从模式搭建

scikit-image image processing notes

淘宝宝贝页面制作
D45_Camera assembly Camera

白鹭egret添加新页面教程,如何添加新页面

Email management Filter emails

System basics - study notes (some command records)
![In-depth analysis if according to data authority @datascope (annotation + AOP + dynamic sql splicing) [step by step, with analysis process]](/img/b5/03f55bb9058c08a48eae368233376c.png)
In-depth analysis if according to data authority @datascope (annotation + AOP + dynamic sql splicing) [step by step, with analysis process]

矩阵的构造
随机推荐
Collision, character controller, Cloth components (cloth), joints in the Unity physics engine
vscode笔记
获取预训练模型的网络输入尺寸
Tips for formatting code indentation
数组&的运算
Come, come, let you understand how Cocos Creator reads and writes JSON files
ALC experiment
【5】Docker中部署MySQL
cs231n learning record
Redis的使用
Native JS takes you to understand the implementation and use of array methods
MySQL的主从模式搭建
前置++和后置++的区别
h5页面回退到微信小程序并携带参数
uniapp打包次数限制怎么办?只需两步就能解决
D41_buffer pool
盒子模型小练习
LeetCode练习及自己理解记录(1)
Media query, rem mobile terminal adaptation
2022最强版应届生软件测试面试攻略