![](/img/trans.png)
[英]How to use node js util.promisify with the writeFile fs function and await
[英]How to promisify and await for setImmediate in Node?
我一直在閱讀有關如何不阻止 Node 的事件循環的信息。 避免阻塞的一種方法是使用分區。
我試圖在我的代碼中使用分區循環,但我似乎無法等待我的循環。 這是我的代碼的簡化版本:
const report = {
someValue: 0
};
const runLoop = async () => {
report.someValue += 1;
// all sorts of async operations here that use async-await
if (report.someValue < 1000) {
await setImmediate(runLoop);
}
};
await runLoop();
console.log('Report is', report);
這將返回“Report is { someValue: 1 }”,但我希望 someValue 為 1000。
我猜 setImmediate 不會返回 promise,所以我嘗試過承諾它:
const setImmediatePromise = util.promisify(setImmediate);
const report = {
someValue: 0
};
const runLoop = async () => {
report.someValue += 1;
// all sorts of async operations here that use async-await
if (report.someValue < 1000) {
await setImmediatePromise(runLoop);
}
};
await runLoop();
console.log('Report is', report);
但這也會返回“Report is { someValue: 1 }”。
那么,我怎樣才能等待這個遞歸 setImmediate “循環”,以便我僅在整個遞歸周期完成后才進行 console.log 報告?
當您承諾setImmediate
,您不再向它傳遞回調。 相反,您只需await
它返回的 promise。 然后你會做遞歸調用:
async function runLoop() {
…
if (…) {
await setImmediatePromise();
return runLoop();
}
}
但是, async
/ await
使您能夠編寫一個實際的循環:
const setImmediatePromise = util.promisify(setImmediate);
const report = {
someValue: 0
};
while (report.someValue < 1000) {
report.someValue += 1;
// all sorts of synchronous operations here
await setImmediatePromise();
}
console.log('Report is', report);
(注意遞歸的細微差別:在第一次迭代之前已經檢查了條件,並且setImmediate
在最后一次迭代之后再次運行。使用do
/ while
甚至while(true)
+ if(…)break;
如有必要。 )
順便說一句,如果您已經在循環內執行異步(非阻塞)操作,則沒有理由向其添加額外的setImmediate
。 該指南僅處理會阻塞事件循環的復雜同步計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.