- 你需要先了解 Promise扫茅。
- 本質是
Generator
的語法糖。
參考
作用
簡化
Promise
的使用過程育瓜。讓你的異步代碼看起來像是同步的葫隙。
async
async
位于函數(shù)字面量或函數(shù)表達式的前面(普通函數(shù)、立即執(zhí)行函數(shù)和箭頭函數(shù)均可)躏仇,被修飾函數(shù)執(zhí)行后會返回一個Promise
對象恋脚。-
例子:
async function chloe() { console.log("chloe"); return 20; } 等價于 function chloe() { return new Promise((resolve, reject) => { console.log("chloe"); resolve(20); }); }
函數(shù)體內返回值則作為
resolve
的參數(shù)。函數(shù)體內拋出錯誤焰手,則錯誤信息作為
reject
的參數(shù)糟描。
await
await
一定要位于async
函數(shù)內部。await
一般位于Promise
對象之前书妻,所以一般位于async
函數(shù)執(zhí)行的前面船响,但若是返回值為Promise
對象的普通函數(shù)也可。await
會拿到該對象的結果躲履,也就是then
中resolve
或reject
的參數(shù)见间。如果不是Promise
對象,則直接返回對應的值工猜。若
await
后方不是Promise
對象米诉,則會將其用Promise.resolve
包裝后執(zhí)行。await
的執(zhí)行會被強制等待至拿到結果域慷,后續(xù)函數(shù)體內的代碼執(zhí)行被阻塞荒辕,函數(shù)本身不會阻塞整體代碼汗销。
async function chloe() {
console.log("chloe");
return 20;
}
async function taran() {
const age = await chloe(); chloe函數(shù)執(zhí)行返回出一個Promise對象犹褒,await拿到該對象resolve的參數(shù)20,賦值給age
console.log("taran" + age);
}
taran(); chloe taran20
async function chloe() {
console.log("chloe");
throw 18;
}
async function taran() {
try {
const age = await chloe(); chloe函數(shù)執(zhí)行返回出一個Promise對象弛针,await拿到該對象reject的參數(shù)18
console.log("taran" + age); 不再執(zhí)行
} catch (error) {
console.log("taran" + error); 捕獲到錯誤信息18
}
}
taran(); chloe taran18