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

前端 未结 7 2175
执笔经年
执笔经年 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:48

    I found Dmitry's answer using the async utility library very useful and the best answer.

    This answer expands his example to a working version that defines the apiMethod function and passes it a parameter. I was going to add the code as a comment but a separate answer is clearer.

    const async = require('async');
    
    const apiMethod = function(uri, callback) {
      try {
        // Call your api here (or whatever thing you want to do) and assign to result.
        const result = ...
        callback(null, result);
      } catch (err) {
        callback(err);
      }
    };
    
    const uri = 'http://www.test.com/api';
    
    async.retry(
        { times: 5, interval: 200 },
        function (callback) { return apiMethod(uri, callback) },
        function(err, result) {
          if (err) {
            throw err; // Error still thrown after retrying N times, so rethrow.
          }
      });
    

    Retry documentation: https://caolan.github.io/async/docs.html#retry

    Note, an alternative to calling apiMethod(uri, callback) in the task is to use async.apply:

    async.retry(
            {times: 5, interval: 200},
            async.apply(task, dir),
            function(err, result) {
              if (err) {
                throw err; // Error still thrown after retrying N times, so rethrow.
              }
          });
    

    I hope this provides a good copy/paste boiler plate solution for someone.

提交回复
热议问题