2 回答

TA貢獻1877條經驗 獲得超6個贊
Usingthen是最簡單的解決方案,但您可以使用AIIFE:
function test() {
(async () => {
const users = await getUsersFromDB();
console.log(users);
})().catch(console.error);
console.log('The rest of the code here continues to execute');
[...]
// Promise resolves and logs the users value
}
替代方案只能是async do表達式。

TA貢獻1784條經驗 獲得超2個贊
所以你需要的基本上是拆分代碼。一件應該以 async/await 語法執行,另一件應該照常執行。
首先我想說的話,如果你這樣做如下
async function test() {
console.log('The rest of the code here continues to execute');
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
這樣就可以了。這可能看起來有點奇怪,因為我們只是將線路向上移動了一點,這不是我們想要做的,但是......
await關鍵字停止函數的執行async,但是我們有一些代碼在凍結函數時應該繼續工作await,這意味著我們不能將代碼放在 之后await,只能放在之前。
據我了解,表示為“這里的其余代碼繼續執行”的代碼也可以是異步的,因此生成的示例如下:
async function test() {
console.log('Some synchronous code');
setImmediate(() => {
console.log('Some asynchronous code');
});
const users = await getUsersFromDB();
// Code in here is not executed until promises returns
console.log(users);
}
添加回答
舉報