Promise - try until it succeds [duplicate]

2019-02-19 18:07发布

问题:

This question already has an answer here:

  • Promises: Repeat operation until it succeeds? 5 answers

I'm using native node.js's Promises and the question here did give me any point. Basically, I have a function like below:

var foo = foo (resolve, reject) {
    return obj
        .doA()
        .doB()
        .then(function (value) {
            // here I choose if I want to resolve or reject.
        })
        .catch(function(err) {
        });
}

var promise = new Promise(foo);

return promise
    .then(function() {
        // I know here what I have to return.
    })
    .catch(function(err){
        // I want to repeat the foo function until it is resolved and not rejected. 
    })

obj is a promised object. I would to like to retry the foo function as long as the promise is fulfilled; if it's rejected, then try again.

I do not know how to structure the chain. Any help? Thanks.

回答1:

Try including function in declaration of foo , using recursion

function foo() {

  var n = String(new Date().getTime()).slice(-1);
  // if `n` < 5 reject `n` , else resolve `n`
  return Promise[n < 5 ? "reject" : "resolve"](n)
    .then(function(value) {
      return value
        // here I choose if I want to resolve or reject.
    })
    .catch(function(err) {
      return Promise.reject(["rejected", err])
    });
}

(function repeat() {
  var promise = Promise.resolve(foo());

  return promise
    .then(function(data) {
      console.log("complete", data)
        // I know here what I have to return.
    })
    .catch(function(err) {
        // I want to repeat the foo function until it is resolved and not rejected. 
      console.log(err);
      if (err[0] === "rejected") repeat()
    })
}())