0

I have some async work that can fail and be rejected. I would like to retry until it gets resolved. Have found this approach but cant make it work. dontGiveUp(doFirst) gives me: Uncaught TypeError: f.then is not a function(…)

Can someone point the errors/or better aproach?

function dontGiveUp(f) {
    return f.then(
        undefined, 
        function (err) {
                return dontGiveUp(f); 
        }
    );
}



function doFirst(In){
return new Promise(function(resolve, reject) {
    console.log("doFirst Done" + In);    
    if (Math.random() >= 0.5) {
        console.log("resolve");    
        resolve(In);
    }
    else
    {
    console.log("reject");    
    reject(In);  
    }
})
}
Jose Neto
  • 329
  • 1
  • 2
  • 8

1 Answers1

3

One possibility is to keep calling the promise resolver function until it's resolved:

function stubborn(promisedFunc) {
    var args = Array.from(arguments);
    return promisedFunc.apply(null, args.slice(1)).catch(function() {
      return stubborn.apply(null, args);
    });
};


rnd = function(a, b) {
    return new Promise(function(res, rej) {
        var x = Math.random();
        document.write('trying ' + x + '<br>');
        if(x > a && x < b)
            res(x)
        else
            rej();
    })
};

stubborn(rnd, 0.3, 0.4).then(function(x) {
    document.write('finally ' + x + '!')
});
georg
  • 211,518
  • 52
  • 313
  • 390
  • This works :-) Just one question:how would you pass arguments to the function being tried? If I do something like: stubborn(rnd(args)) gets me errors like" Uncaught (in promise) TypeError: Cannot read property 'then' of undefined(…)" – Jose Neto Mar 04 '16 at 10:34
  • Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Jun 17 '16 at 08:55
  • @georg: Something like `return promisedFunc.apply(this, args).then(null, function(err) { return stubborn.apply(promiseFunc, args); })` – Bergi Jun 17 '16 at 10:35