Promises: Repeat operation until it succeeds?

前端 未结 6 900
天命终不由人
天命终不由人 2020-11-30 08:28

I want to perform an operation repeatedly, with an increasing timeout between each operation, until it succeeds or a certain amount of time elapses. How do I structure this

6条回答
  •  心在旅途
    2020-11-30 09:16

    My sugesstion would be to use the bluebird-retry library

    To install

    npm i bluebird-retry

     var Promise = require('bluebird');
     var retry = require('bluebird-retry');
     var count = 0;
    function myfunc() {
        console.log('myfunc called ' + (++count) + ' times '+new Date().toISOString());
        return Promise.reject(new Error(''));
    }
    retry(myfunc,{ max_tries: 5, interval: 5000, backoff: 2 })
        .then(function(result) {
            console.log(result);
        });
    

    The above program tries the promise flow 5 times with interval * backoff backoff interval between every retry.

    Also, should you require to pass any arguments, pass it as args which accepts array of arguments. Include it in options section where max_retries, interval and backoff is mentioned.

    Here is the official documentation https://www.npmjs.com/package/bluebird-retry

提交回复
热议问题