当前位置:网站首页>Promise (3) async/await
Promise (3) async/await
2022-08-05 06:56:00 【Do you want to buy groceries?】
async 函数
async 函数是使用async关键字声明的函数. async 函数是AsyncFunction构造函数的实例, 并且其中允许使用await关键字.async和await关键字让我们可以用一种更简洁的方式写出基于Promise的异步行为,而无需刻意地链式调用promise.
特点
1. 函数的返回值为 promise 对象
2. promise 对象的结果由 async 函数执行的返回值决定
async function main(){
//1. 如果返回值是一个非Promise类型的数据,会返回一个resolved的promise对象,value is the data
// return 521;
//2. 如果返回的是一个Promise对象
return new Promise((resolve, reject) => {
resolve('OK');
// reject('Error');
});
//3. 抛出异常
// throw "Oh NO";
}
let result = main();
console.log(result);await 表达式
1. await 右侧的表达式一般为 promise 对象, 但也可以是其它的值
2. 如果表达式是 promise 对象, await 返回的是 promise 成功的值
3. 如果表达式是其它值, 直接将此值作为 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();注意
1. await 必须写在 async 函数中, 但 async 函数中可以没有 await
2. 如果 await 的 promise 失败了, 就会抛出异常, 需要通过 try...catch 捕获处理
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
// Errors do not need to be judged at every level,使用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();边栏推荐
- Redis
- 香港国际珠宝展及香港国际钻石、宝石及珍珠展揭幕
- Japan Sanitary Equipment Industry Association: Japan's warm water shower toilet seat shipments reached 100 million sets
- The cocos interview answers you are looking for are all here!
- VS Code私有服务器部署(私有化)
- 17-VMware Horizon 2203 虚拟桌面-Win10 手动桌面池浮动(十七)
- 格式化代码缩进的小技巧
- Writing OpenCV in VSCode
- VSCode编写OpenCV
- 【Go】IM系统Centrifugo
猜你喜欢
随机推荐
typescript61-泛型工具类型(pick)
## 简讲protobuf-从原理到使用
盒子模型中过度约束问题及其解决办法
Unable to import torchvision. IO. Read_image
Nacos集群搭建
LaTeX image captioning text column automatic line wrapping
Pytorch distributed parallel processing
在小程序中关于js数字精度丢失的解决办法
Tips for formatting code indentation
概率与期望部分题解
盒子模型小练习
白鹭egret添加新页面教程,如何添加新页面
NB-IOT智能云家具项目系列实站
淘宝宝贝页面制作
LaTeX 图片加标题 文本分栏自动换行
typescript66-分析partial的实现
香港国际珠宝展及香港国际钻石、宝石及珍珠展揭幕
不太会讲爱,其实已经偷偷幸福很久啦----我们的故事
文件内音频的时长统计并生成csv文件
边缘盒子+时序数据库,美的数字化平台 iBUILDING 背后的技术选型









