当前位置:网站首页>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();边栏推荐
猜你喜欢
随机推荐
MySQL:JDBC编程
Rapid Medical超小体积且唯一可调的取栓器获得FDA核准
vscode notes
D45_Camera assembly Camera
浮点数基础知识
利用将网页项目部署到阿里云上(ngnix)
盒子模型小练习
export使用
Shared memory + inotify mechanism to achieve multi-process low-latency data sharing
h5页面回退到微信小程序并携带参数
LaTeX image captioning text column automatic line wrapping
UI刘海屏适配方式
亚马逊美国站:马术头盔CPC认证标准要求
typescript67-索引查询类型
无法导入torchvision.io.read_image
scikit-image image processing notes
字体样式及其分类
17-VMware Horizon 2203 virtual desktop-Win10 manual desktop pool floating (seventeen)
ndk编译so库
获取预训练模型的网络输入尺寸









