chaining recursive promise with bluebird

后端 未结 1 1263
悲&欢浪女
悲&欢浪女 2021-01-12 12:07

I have a promise chain with a recursive promise doAsyncRecursive() in the middle like so:

doAsync().then(function() {
    return doAsyncRecursive();
}).then(         


        
相关标签:
1条回答
  • 2021-01-12 12:29

    Catch the failure, wait five seconds, then try again.

    function doAsyncRecursive() {
        return doAsyncThing().catch(function() {
            return Promise.delay(5000).then(doAsyncRecursive);
        });
    }
    

    Here doAsyncThing is a function corresponding to the //do async thing comment in the OP's code, defined as returning a promise. In the original code, the success or failure of the "do async thing" is tested using a success flag, but by definition asynchronous routines do not deliver such a flag; they deliver their results either via a callback or a promise. The code above assumes that doAsyncThing returns a promise. It also assumes that "failure", in the sense of "does not return the response i want", is represented by that promise rejecting. If instead "success" or "failure" is to be defined as some particular value of a fulfilled promise, then you'd want to do

    function doAsyncRecursive() {
        return doAsyncThing().then(function(success) {
            if (success) return success;
            else return Promise.delay(5000).then(doAsyncRecursive);
        });
    }
    
    0 讨论(0)
提交回复
热议问题