0

I have a function that results in a lot of errors so I have to call it many times before it finally gives the right result. It returns a promise so I created a wrapper around it that recursively keeps calling it upon rejection.

I want to return a new Promise created via Bluebird but which has to reject after a set timeout. And it has to keep calling that above function repeatedly. But before each repetition I want to check whether it was auto-rejected due to timeout.

Bluebird has a isRejected() method but it seems I can't use it from within the promise body:

var promise = new Promise(function(resolve, reject){
    var self = this;
    setTimeout(reject, TIMEOUT*1000);
    return doSomethingWrapper();
    function doSomethingWrapper(){

        if(promise.isRejected()) return;
        // Error: Cannot read property 'isRejected' of undefined

        if(self.isRejected()) return;
        // Error: self.isRejected is not a function

        return doSomething().then(resolve, doSomethingWrapper).catch(doSomethingWrapper);
    }
});

Any other solution?

Community
  • 1
  • 1
laggingreflex
  • 32,948
  • 35
  • 141
  • 196
  • It doesn’t make sense to use it from within the promise body, and since `doSomethingWrapper` is called immediately, there is no way the `setTimeout` callback will have fired so it’s not necessary to check anyway. – Ry- Aug 24 '15 at 01:51

2 Answers2

1

Create the timeout promise:

var timeout = Bluebird.delay(TIMEOUT * 1000).then(function () {
    return Bluebird.reject(new Error("Timed out"));
});

Create the operation promise:

var something = (function doSomethingWrapper() {
    if (timeout.isRejected()) {
        return;
    }

    return doSomething().catch(doSomethingWrapper);
})();

Race them:

var promise = Bluebird.race(something, timeout);
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

This can actually be done in a simpler fashion:

Promise.try(function doSomethingWrapper(){ 
   return doSomething().catch(doSomethingWrapper); // retry
}).timeout(TIMEOUT * 1000);

No need for races :)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504