亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

異步/等待語法:有沒有辦法定義一個代碼塊在函數之后執行而不阻塞執行?

異步/等待語法:有沒有辦法定義一個代碼塊在函數之后執行而不阻塞執行?

烙印99 2022-07-21 10:41:38
我最近一直在問自己如何使用 async/await 語法重現 then/catch 的行為。使用 then/catch,我可以定義一個回調,該回調僅在 Promise 解決時執行,然后像這樣繼續執行。function test() {    getUsersFromDB().then(users => console.log(users));    console.log('The rest of the code here continues to execute');    [...]    // Promise resolves and logs the users value}對我來說,使用 async/await 你可以有兩種可能的行為。1.等待函數并阻塞其余的執行async function test() {   const users = await getUsersFromDB();    // Code in here is not executed until promises returns    console.log(users);}2. 不要等待返回值,但不要期望你的承諾會在其余代碼執行時實現function test() {    const users = getUsersFromDB();    // May log undefined    console.log(users);}我可以使用 async/await 重現第一個用例嗎?
查看完整描述

2 回答

?
慕哥9229398

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表達式。


查看完整回答
反對 回復 2022-07-21
?
一只斗牛犬

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);

}


查看完整回答
反對 回復 2022-07-21
  • 2 回答
  • 0 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號