简体   繁体   English

如何使用 Promise 实现异步无限循环

[英]How to have an async endless loop with Promises

I need to have an "endless" while-loop which has promises inside it.我需要一个“无休止的”while 循环,里面有承诺。 Here's some example code:下面是一些示例代码:

let noErrorsOccured = true

while (noErrorsOccured){
    someAsyncFunction().then(() => {
        doSomething();
    }).catch((error) => {
        console.log("Error: " + error);
        noErrorsOccured = false;
    });
}

function someAsyncFunction() {
    return new Promise ((resolve, reject) => {
        setTimeout(() => {
            const exampleBool = doSomeCheckup();
            if (exampleBool){
                resolve();
            } else {
                reject("Checkup failed");
            }
        }, 3000);
    });
}

So this while-loop should run endless, except an error occurs, then the while-loop should stop.所以这个while循环应该无休止地运行,除非发生错误,然后while循环应该停止。 How can I achieve this?我怎样才能做到这一点?

I hope you can understand what I mean and thanks in advance.我希望你能理解我的意思,并提前致谢。

How can I achieve this?我怎样才能做到这一点?

Not with a blocking loop since promises won't be able to settle.没有阻塞循环,因为承诺将无法解决。 You can learn more about JavaScript's event loop on MDN .您可以在 MDN 上了解有关JavaScript 事件循环的更多信息。

Instead, call the function again when the promise is resolved:相反,当 promise 被解析时再次调用该函数:

Promise.resolve().then(function resolver() {
    return someAsyncFunction()
    .then(doSomething)
    .then(resolver);
}).catch((error) => {
    console.log("Error: " + error);
});

This is what worked for me (based on discussion here: https://github.com/nodejs/node/issues/6673 ) in NodeJS:这对我有用(基于这里的讨论: https : //github.com/nodejs/node/issues/6673 )在 NodeJS 中:

async function run(){
  // Do some asynchronous stuff here, e.g.
  await new Promise(resolve => setTimeout(resolve, 1000));
}

(function loop(){
   Promise.resolve()
     .then(async () => await run())
     .catch(e => console.error(e))
     .then(process.nextTick(loop));
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM