当前位置:网站首页>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();
边栏推荐
猜你喜欢
矩阵的构造
Detailed explanation of the construction process of Nacos cluster
Cocos Creator Mini Game Case "Stick Soldier"
Some basic method records of commonly used languages in LeetCode
The future of cloud gaming
人人AI(吴恩达系列)
淘宝宝贝页面制作
export使用
After docker is deployed, mysql cannot connect
lingo入门——河北省第三届研究生建模竞赛B题
随机推荐
Freeswitch操作基本配置
Tencent Internal Technology: Evolution of Server Architecture of "The Legend of Xuanyuan"
数组&的运算
The future of cloud gaming
Cloud Computing Basics - Study Notes
D39_ coordinate transformation
lingo入门——河北省第三届研究生建模竞赛B题
Pytorch distributed parallel processing
D45_Camera assembly Camera
字体样式及其分类
邮件管理 过滤邮件
What is the website ICP record?
export使用
网络排错基础-学习笔记
Native JS takes you to understand the implementation and use of array methods
## 简讲protobuf-从原理到使用
HelloWorld
摆脱极域软件的限制
reduce()方法的学习和整理
Error correction notes for the book Image Processing, Analysis and Machine Vision