async/await
async 用于申明一個 function 是異步的溶推,而 await 用于等待一個異步方法執(zhí)行完成徊件。
await 只能出現(xiàn)在 async 函數(shù)中。
async
//普通方法
function fn() {
return 'Hello world'
};
let result1 = fn();
console.log(result1); //Hello world
//async方法
async function fn2() {
return 'Hello world'
};
let result2 = fn2();
console.log(result2); //Promise對象
result2.then(value => {
console.log(value); //Hello world
});
根據(jù)上面可以看到蒜危,如果直接return 虱痕,async會調用Promise.resolve() 封裝成 Promise 對象
Promise.resolve('Hello world')
等價于 new Promise(resolve => resolve('Hello world'))
await
await是在等待一個async函數(shù)的返回值,不僅僅用于等 Promise 對象辐赞,它可以等任意表達式的結果部翘,所以,await 后面實際是可以接普通函數(shù)調用或者直接量的响委。
async function getSomething() {
return "something";
}
function testPromise() {
return Promise.resolve("hello async");
}
async function test() {
const v1 = await getSomething();
const v2 = await testPromise();
console.log(v1, v2); //something hello async
}
test();
await
是個運算符新思,用于組成表達式,await 表達式的運算結果取決于它等的東西晃酒。- 因為testPromise返回的就是Promise對象表牢, 在前面可以不用加
async
- 上面
async
函數(shù)中,如果是直接return一個結果贝次,會返回一個promise對象崔兴,但是當await
等到是一個promise對象,會得到對象中resolve的值,作為await
的運算結果
async/await 的優(yōu)勢
假設一個業(yè)務敲茄,分多個步驟完成位谋,每個步驟都是異步的,而且依賴于上一個步驟的結果堰燎。我們?nèi)匀挥?setTimeout
來模擬異步操作:
/**
* 傳入?yún)?shù) n掏父,表示這個函數(shù)執(zhí)行的時間(毫秒)
* 執(zhí)行的結果是 n + 200,這個值將用于下一步驟
*/
function takeLongTime(n) {
return new Promise(resolve => {
setTimeout(() => resolve(n + 200), n);
});
}
function step1(n) {
console.log(`step1 with ${n}`);
return takeLongTime(n);
}
function step2(n) {
console.log(`step2 with ${n}`);
return takeLongTime(n);
}
function step3(n) {
console.log(`step3 with ${n}`);
return takeLongTime(n);
}
- 現(xiàn)在用 Promise 方式來實現(xiàn)這三個步驟的處理
function doIt() {
const time1 = 300;
step1(300).then(time2 => {
step2(time2).then(time3 => {
step3(time3).then(result => {
console.log(`result is ${result}`);
})
})
})
};
doIt();
//step1 with 300
//step2 with 500
//step3 with 700
//result is 900
- async/await 實現(xiàn)
async function doIt() {
const time1 = 300;
const time2 = await step1(time1);
const time3 = await step2(time2);
const result = await step3(time3);
console.log(`result is ${result}`);
};
doIt();
//結果一樣秆剪,結構更清晰赊淑,幾乎和同步代碼一樣;
?