我正在開發一個使用 express 和 node js 構建的專案。我只需要在 SetTimeout 函式中呼叫異步函式(回呼)
這是我的控制器檔案
module.exports.create = async (req, res) => {
try {
// Some DB Calls
setTimeout(() => updateWhOrders(req.Orders, req), 0)
// Some DB Calls
return res.status(200).json({ data , msg: "record created successfully", success: true })
} catch (error) {
if (error?.message?.includes("Validation error")) {
return handleErr({ message: "This supplier order id has already been added. Please refresh the page and check further down the screen." }, res)
}
return handleErr(error, res)
}
}
這是同一個控制器中的異步函式
const updateWhOrders = async (allOrders, req) => {
// Some DB Calls using async await
await SourceOrder.bulkCreate(allOrders.data, { updateOnDuplicate: ["wh_address"] })
}
現在我想問一下這兩種說法的區別
1. setTimeout(() => updateWhOrders(req.Orders, req), 0)
2. updateWhOrders(req.Orders, req)
我只想在將回應發送回 API 之前并行呼叫 updateWhOrders 函式。
使用 setTimeout 函式有什么特殊原因嗎?或者,如果我省略 setTimeout 函式,它的行為將與使用 setTimeout 函式完全相同?
根據我的理解,如果我省略 setTimeout 函式,它將通過回傳一個承諾在后臺運行。如果我在 setTimeout 函式中呼叫 function(updateWHOrders) 會怎樣。有什么好處?如果我錯了,請糾正我。
先感謝您 :)
uj5u.com熱心網友回復:
你不應該setTimeout在這里使用:它不會并行執行回呼,但稍后,在其余同步代碼執行后。
相反,如果它是唯一需要在呼叫 之前發生的異步任務res.status(200),則使用await:
await updateWhOrders(req.Orders, req);
如果您有更多的異步任務,并且它們彼此獨立,以便它們可以按任何順序執行——并且不必等待對方的結果——然后使用Promise.all:
await Promise.all([
updateWhOrders(req.Orders, req),
anotherAsyncFunc(),
yetAnotherAsyncFunc()
]);
區別與 setTimeout
您詢問了這些陳述之間的區別:
setTimeout(() => updateWhOrders(req.Orders, req), 0)
updateWhOrders(req.Orders, req)
第一個updateWhOrders現在不會呼叫,但會在所有同步代碼執行后安排它執行。這可能是在 nextawait執行之后,或者如果沒有,則在 thereturn執行之后。呼叫堆疊必須先變空,然后updateWhOrders才能執行。
第二個將updateWhOrders立即執行。
也不使用updateWhOrders回傳承諾的事實,因此這方面沒有得到很好的處理。你會想知道內部 的異步呼叫什么時候updateWhOrders完成它的作業,為此你需要對回傳的承諾做一些事情。這就是為什么你應該使用.then, await, Promise.all, ... 或任何處理該承諾的東西。
uj5u.com熱心網友回復:
哈薩姆。setTimeoutmain函式是呼叫一個函式asynchronously。它回傳一個promise并且是new PromiseNodeJs 中函式的替換。談到您的問題,在這里您不想進行updateWhOrders功能阻塞,而是希望在不阻塞其他代碼部分的情況下在單獨的執行緒中運行它。盡管 NodeJs 是一種單執行緒語言,但它使用相同的執行緒來處理同步和異步呼叫,并且使用事件回圈來處理它們。要了解有關事件回圈的更多資訊,您可以觀看此視頻:https : //youtu.be/8aGhZQkoFbQ
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/373144.html
