Promise - try until it succeds [duplicate]

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.

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.