How to do repeated requests until one succeeds without blocking in node?

前端 未结 7 2017
执笔经年
执笔经年 2021-01-31 17:35

I have a function that takes a parameter and a callback. It\'s supposed to do a request to a remote API and get some info based on the parameter. When it gets the info, it needs

7条回答
  •  一生所求
    2021-01-31 17:40

    There is no need to re-invent the wheel... you can use a popular async utility library, 'retry' method in this case.

    // try calling apiMethod 3 times
    async.retry(3, apiMethod, function(err, result) {
        // do something with the result
    });
    
    // try calling apiMethod 3 times, waiting 200 ms between each retry
    async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
        // do something with the result
    });
    

    async GitHub page

    async.retry docs

提交回复
热议问题