Thaina Thaina - 4 months ago 9
Javascript Question

Can we get current promise in then?

I want to have some mechanism to redo then function in promise. Keep doing it until it pass some check

somePromise.then(() => {
if(state == "finish")
return;

// DoSomething async then repeat these codes
// could we do it by [return this;] ?
}).then(() => console.log("finish"));

Answer

You can name the function used at .then(), recursively call same function at .then() of doSomethingAsync() call until state == "finish"

// name function used at `.then()` 
somePromise.then(function re(data) {
    if(state == "finish") {
        return data;
    };
    // DoSomething async then repeat these codes
    // call `re` at `.then()` chained to `doSomethingAsync()`
    doSomethinAsync().then(re);
}).then((data) => console.log("finish", data));

See also multiple, sequential fetch() Promise