簡體   English   中英

如何在 Node 中承諾和等待 setImmediate?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM