How to have an async endless loop with Promises

China☆狼群 提交于 2020-02-03 05:16:06

问题


I need to have an "endless" while-loop which has promises inside it. 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. How can I achieve this?

I hope you can understand what I mean and thanks in advance :)


回答1:


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.

Instead, call the function again when the promise is resolved:

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


来源:https://stackoverflow.com/questions/39894777/how-to-have-an-async-endless-loop-with-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!