简体   繁体   中英

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

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

    })

}

Pormise 是异步的,因此 then 中的代码将在此事件循环结束时运行

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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