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

互換的青春
TA貢獻1797條經驗 獲得超6個贊
你需要等待。實際上“async/await”只是一個語法糖。你的 updateOtherThings 函數實際上返回一個 Promise,如果你不等待它,那么它就不會運行。如果你只是想開始并忘記它,那么寫如下:
updateOtherThings().then(() => {});
添加回答
舉報
0/150
提交
取消