参考资料 :https://www.jianshu.com/p/1e75bd387aa0
要点:
1. async function(){} 将普通函数转换成Promise
2. await 表达式/函数 强制等待后面的结果返回再继续
3. await 只能用在async function(){}中 ,用在普通函数中会报错
async function add1(x){
let a =1;
return x+a;
}
add1(10)
Promise {<resolved>: 11}
async声明add1是一个Promise,执行函数,可以看出
add1(10)的返回值是一个resoved的Promise
function pm(){
return new Promise((resolve,reject)=>{
resolve('1')
}) }; async function test(){
let a = await pm();
let b = await '2';
console.log(a)
console.log(b)
return a+b;
} test()
1 2
Promise {<resolved>: "12"}
4. 报错处理:最好把await 放入try ... catch ... 中
function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(() => {reject('error')}, ms); //reject模拟出错,返回error }); } async function asyncPrint(ms) { try { console.log('start'); await timeout(ms); //这里返回了错误 console.log('end'); //所以这句代码不会被执行了 } catch(err) { console.log(err); //这里捕捉到错误error } } asyncPrint(1000);
下面这种方法也可以:
function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(() => {reject('error')}, ms); //reject模拟出错,返回error }); } async function asyncPrint(ms) { console.log('start'); await timeout(ms) console.log('end'); //这句代码不会被执行了 } asyncPrint(1000).catch(err => { console.log(err); // 从这里捕捉到错误 });
如果想让
console.log('end'); 继续执行,那么可以提前cathc错误
function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(() => { reject('error') }, ms); //reject模拟出错,返回error }); } async function asyncPrint(ms) { console.log('start'); await timeout(ms).catch(err => { // 注意要用catch console.log(err) }) console.log('end'); //这句代码会被执行 } asyncPrint(1000);
应用场景:
当出现多个await 时,如果不存在依赖关系,可以用Promise.all() 并发处理,速度要比一直等待快。
function test1 () {
return new Promise((resolve, reject) => { setTimeout(() => { resolve(1) }, 1000) }) } function test2 () { return new Promise((resolve, reject) => { setTimeout(() => { resolve(2) }, 2000) }) } async function exc1 () { console.log('exc1 start:',Date.now()) let res1 = await test1(); let res2 = await test2(); // 不依赖 res1 的值 console.log('exc1 end:', Date.now()) } async function exc2 () { console.log('exc2 start:',Date.now()) let [res1, res2] = await Promise.all([test1(), test2()]) console.log('exc2 end:', Date.now()) } exc1(); exc2();