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

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

我需要等待我的異步函數,然后返回嗎?

我需要等待我的異步函數,然后返回嗎?

POPMUISE 2023-08-05 20:43:56
我有兩個功能。1.async function firstFunction() {  // Do stuff here  // I can't just return doSomeOtherThings because the firstFunction  // returns different data then what doSomeOtherThings does  doSomeOtherThings();  return;}async function doSomeOtherThings() {  // do promise stuff here  // this function runs some db operations}如果我運行,firstFunction();它會執行我的doSomeOtherThings()函數,還是會提前返回并導致部分或全部 doSomeOtherThings 代碼不被執行?我需要做什么嗎await doSomeOtherThings()?
查看完整描述

2 回答

?
料青山看我應如是

TA貢獻1772條經驗 獲得超8個贊

我認為這里有點混亂,所以我會嘗試從頭開始。


首先,異步函數總是返回一個承諾。如果您在其中添加另一個異步函數,您可以鏈接它們并在返回第一個承諾之前等待響應。但是,如果您不等待內部函數,則第一個函數將在第二個函數仍在運行時解析。


async function firstFunction() {

  if (I want to wait for doSomeOtherThings to finished before ending firstFunction){

    await   doSomeOtherThings();

  } else if (I can finish firstFUnction and let doSomeOtherTHings finish later){

    doSomeOtherThings

  }


  return;

}


async function init() {

  const apiResponse = await firstFunction();

};


init();


查看完整回答
反對 回復 2023-08-05
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

你需要等待。實際上“async/await”只是一個語法糖。你的 updateOtherThings 函數實際上返回一個 Promise,如果你不等待它,那么它就不會運行。如果你只是想開始并忘記它,那么寫如下:

    updateOtherThings().then(() => {});


查看完整回答
反對 回復 2023-08-05
  • 2 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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