3

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"));
Thaina Yu
  • 1,372
  • 2
  • 16
  • 27
  • 2
    `var retry = fn => _ => fn().catch(retry(fn));` - and have fn throw if check failed ... usage: `retry(fn).then(ok => console.log(ok));` – Jaromanda X Aug 04 '16 at 03:40
  • Wait so do you want to re-run `somePromise.then(() => {` IF some condition inside the first `.then` is satisfied? – James111 Aug 04 '16 at 03:48

2 Answers2

3

In general, you don't get access to the current promise inside the .then() handler. And, for the most part, you couldn't do anything useful anyway. Adding another .then() handler does not do anything different than the .then() handler you're already in. Once fulfilled, promises never change their state.

If you want to repeat something, you make a function out of the thing you want to repeat and you call it over again from within the .then() handler and you return the resulting promise (thus chaining it to the previous promise).

Here's an example:

// utility delay function that returns a promise
function delay(t, val) {
   return new Promise(function(resolve) {
       setTimeout(function() {
           resolve(val);
       }, t);
   });
}

// repeatedly call someAsyncOp() until we see the operation is finished
function repeatUntil(t) {
   return someAsyncOp().then(function(state) {
      if (state !== "finish") {
           return delay(t).then(repeatUntil);
      }
   });
} 

// sample usage
repeatUntil(5000).then(function() {
    // state is finished here
}).catch(function(err) {
    // error here
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

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(data).then(re);
}).then((data) => console.log("finish", data));

See also multiple, sequential fetch() Promise

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177