1、概述
async(異步) 函數(shù)變體
以下是已經(jīng)存在的異步函數(shù)變體。請注意無處不在的 async 關鍵字。
- 異步函數(shù)聲明: async function foo() {}
- 異步函數(shù)表達式: const foo = async function () {};
- 異步函數(shù)定義:let obj = { async foo() {} }
- 異步箭頭函數(shù): const foo = async () => {};
async(異步) 函數(shù)總是返回 Promises
async(異步) 函數(shù)的 Promise 完成狀態(tài):
async function asyncFunc() {
return 123;
}
asyncFunc()
.then(x => console.log(x));
// 123
async(異步) 函數(shù)的 Promise 拒絕狀態(tài):
async function asyncFunc() {
throw new Error('Problem!');
}
asyncFunc()
.catch(err => console.log(err));
// Error: Problem!
通過 await 處理 async(異步) 計算的結果和錯誤
await(只允許在 async(異步) 函數(shù)內部使用)等待其操作對象 Promise 返回:
- 如果 Promise 是完成狀態(tài),await 的結果是完成態(tài)的值。
- 如果 Promise 是拒絕狀態(tài),await 會拋出拒絕值。
處理單個 async(異步) 返回值:
async function asyncFunc() {
const result = await otherAsyncFunc();
console.log(result);
}
// 等價于:
function asyncFunc() {
return otherAsyncFunc()
.then(result => {
console.log(result);
});
}
按順序處理多個 async(異步) 返回值:
async function asyncFunc() {
const result1 = await otherAsyncFunc1();
console.log(result1);
const result2 = await otherAsyncFunc2();
console.log(result2);
}
// 等價于:
function asyncFunc() {
return otherAsyncFunc1()
.then(result1 => {
console.log(result1);
return otherAsyncFunc2();
})
.then(result2 => {
console.log(result2);
});
}
并行處理多個 async(異步) 返回值:
async function asyncFunc() {
const [result1, result2] = await Promise.all([
otherAsyncFunc1(),
otherAsyncFunc2(),
]);
console.log(result1, result2);
}
// 等價于:
function asyncFunc() {
return Promise.all([
otherAsyncFunc1(),
otherAsyncFunc2(),
])
.then([result1, result2] => {
console.log(result1, result2);
});
}