Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 - keep issuing a promise until it resolves without recursion

I have a promise P which checks a condition on the server (email verified).

P can either resolve -> email verified

or fail -> with code email unverified

or fail -> with code other error (email does not exist etc)

I want to create another promise WaitP that will wait for P to either resolve or fail with a code other than email unverified.

so WaitP does:

  1. issue P

    if P resolves, resolve WaitP

    if P fails with code email unverified, go back to 1 (issue P again)

    if P fail with a code other than email unverified, fail WaitP

How can I write such a promise ?

I am hoping for a solution without recursion.

thx!

like image 613
kofifus Avatar asked May 01 '26 19:05

kofifus


1 Answers

Just recursively call your function from the catch handler:

function waitP() {
    return P().catch(function(err) {
        if (err.code == "email unverified")
            return waitP(); // try again
        else
            throw err;
    });
}

You might want to add a counter or a delay to the recursive call though, so that your process doesn't hang if P() quickly and repeatedly fails ad infinitum.

like image 68
Bergi Avatar answered May 03 '26 07:05

Bergi