如何使用Promise进行异步无限循环

时间:2016-10-06 11:27:49

标签: javascript while-loop es6-promise

我需要一个"无尽的" while-loop在里面有承诺。这是一些示例代码:

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);
    });
}

所以这个while循环应该运行无穷,除了发生错误,然后while循环应该停止。我怎样才能做到这一点?

我希望你能理解我的意思并提前感谢:)

2 个答案:

答案 0 :(得分:7)

  

我怎样才能做到这一点?

没有阻止循环,因为承诺无法解决。您可以详细了解JavaScript's event loop on MDN

相反,在解析承诺时再次调用该函数:

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

答案 1 :(得分:0)

这是对我有用的(基于此处的讨论: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));
})();