前言
async用于申明function异步
await用于等待一个异步方法执行完成
一、async的用法
- async函数返回一个 Promise 对象
//一个普通函数
function getData(){
return "Hello World";
}
console.log(getData()) //Hello World
//加上async后
async function getData(){
return "Hello World";
}
console.log(getData()) // Promise {<fulfilled>: "Hello World"}
- async函数内部return语句返回的值,会成为then方法回调函数的参数
async function getData(){
return "Hello World";
}
getData().then(data =>{
console.log(data) //Hello World
})
- async函数内部抛出错误,会导致返回的 Promise 对象变为reject状态,抛出的错误对象会被catch方法回调函数接收到
async function getData(){
throw new Error('出错了');
}
getData().then(v=>{
console.log(v)
})
.catch(e=>{
console.log(e) //Error: 出错了
});
二、await的用法
await 只能出现在 async 函数中
async 函数返回一个 Promise 对象,所以 await 可以用于等待一个 async 函数的返回值——这也可以说是 await 在等 async 函数,但要清楚,它等的实际是一个返回值。注意到 await 不仅仅用于等 Promise 对象,它可以等任意表达式的结果,所以,await 后面实际是可以接普通函数调用或者直接量的。
function getSomething() {
return "something";
}
async function testAsync() {
return Promise.resolve("hello async");
}
async function test() {
const v1 = await getSomething();
const v2 = await testAsync();
console.log(v1, v2); //something hello async
}
test();
await 等到了它要等的东西,一个 Promise 对象,或者其它值,然后呢?我不得不先说,await 是个运算符,用于组成表达式,await 表达式的运算结果取决于它等的东西。
如果它等到的不是一个 Promise 对象,那 await 表达式的运算结果就是它等到的东西。
如果它等到的是一个 Promise 对象,await 就忙起来了,它会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。
三、async/await 的优势在于处理 then 链
function step1(n) {
console.log(`step1 with ${n}`);
return takeLongTime(n);
}
function step2(m, n) {
console.log(`step2 with ${m} and ${n}`);
return takeLongTime(m + n);
}
function step3(k, m, n) {
console.log(`step3 with ${k}, ${m} and ${n}`);
return takeLongTime(k + m + n);
}
async function doIt() {
console.time("doIt");
const time1 = 300;
const time2 = await step1(time1);
const time3 = await step2(time1, time2);
const result = await step3(time1, time2, time3);
console.log(`result is ${result}`);
console.timeEnd("doIt");
}
doIt();