Promise within while loop won't run - causing infinite loop

北战南征 提交于 2021-02-11 15:55:53

问题


I am trying to run a Promise within a while loop. The code after the promise (in the .then) will eventually break the while loop.

However, the promise never runs. The while loop just keeps running infinitely without triggering the promise.

Why is this? Is it impossible to use a promise in a while loop?

A simplified version of code is below

while(relevantRefundRequests.length >= waitList[0].quantity){

    stripe.paymentIntents.create({

    })
    .then(data => {

    ***code that will break while loop

    })

}

回答1:


You can't structure it the way you did because the while() loop will run forever and never allow even the first .then() handler to run (due to timing and event loop reasons). So, you can't just normally break your while loop from within the .then() handler.

If you can use async/await, then this is more straightforward:

while (relevantRefundRequests.length >= waitList[0].quantity) {

    let data = await stripe.paymentIntents.create({ ... });
    if (some condition) {
        break;
    }    
}

Keep in mind that the containing function here will have to be tagged async and will return long before this loop is done so you have to handle that appropriately.

If you can't use async/await, then the code needs to be restructured to use control structures other than a while loop and it would be helpful to see the real code (not just pseudo code) to make a more concrete suggestion for how best to do that. A general idea is like this:

function runAgain() {
    if (relevantRefundRequests.length >= waitList[0].quantity) {
        return stripe.paymentIntents.create({ ... }).then(data => {
            if (some condition to break the cycle) {
                return finalResult;
            } else {
                // run the cycle again
                return runAgain();
            }
        });
    } else {
        return Promise.resolve(finalResult);
    }
}

runAgain().then(finalResult => {
    console.log(finalResult);
}).catch(err => {
    console.log(err);
});



回答2:


Pormise is asynchronous, so the code in then will run at the end of this event loop



来源:https://stackoverflow.com/questions/60682923/promise-within-while-loop-wont-run-causing-infinite-loop

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