在過去的兩天里,我一直在努力解決這個問題。我想關注特定收藏的變化。這些更改的所有邏輯都是異步的。我試圖使 EventEmitter 回呼函式異步但仍以同步方式作業。
偽代碼示例:
const someLogicFunction1 = async () => {
// some logic here
}
const someLogicFunction2 = async () => {
// some logic here
}
const collectionEventEmitter = Collection.watch();
collectionEventEmitter.on('change', async (change) => {
await someLogicFunction1();
await someLogicFunction2(); // has to wait for first function to finish
});
正如我上面解釋的那樣,我嘗試了這種方法,但仍然同步運行。第二個函式通常必須等待第一個函式完成其任務才能使整個代碼正常作業。
編輯:根據我的發現,回呼函式似乎首先獲取所有這些“更改”引數事件物件,然后執行代碼。我實際上需要的是為每個“更改”事件引數執行代碼 - 而不是一次全部執行。
uj5u.com熱心網友回復:
一種解決方案是someLogicFunction1()回傳一個承諾并呼叫someLogicFunction2();第一個函式的 then ,如下所示:
await someLogicFunction1()
.then(function(){
someLogicFunction2();
});
你只需要這樣修改someLogicFunction1();:
someLogicFunction1( )
{
return new Promise( async function( resolve, reject ) {
// Do your stuff here
}); // eo promise
}
不要忘記resolve()在someLogicFunction1函式中。
resolve();
您還可以reject()在someLogicFunction1呼叫此函式時捕獲并捕獲錯誤。
reject();
你可以傳遞一個引數來解決和拒絕,并在你的電話中得到它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448917.html
標籤:javascript 节点.js mongodb 异步 猫鼬
