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

前端 未结 7 2020
执笔经年
执笔经年 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 18:00

    You could try something along the following lines. I'm writing a general idea, you should replace trySomething with your HTTP request.

    function keepTrying(onSuccess) {
      function trySomething(onSuccess, onError) {
        if (Date.now() % 7 === 0) {
          process.nextTick(onSuccess);
        } else {
          process.nextTick(onError);
        }
      }
      trySomething(onSuccess, function () {
        console.log('Failed, retrying...');
        keepTrying(onSuccess);
      });
    }
    
    keepTrying(function () {
      console.log('Succeeded!');
    });
    

    I hope this helps.

提交回复
热议问题