简体   繁体   English

如何重复调用异步 function 直到指定超时?

[英]How to repeatedly call asynchronous function until specified timeout?

I want to keep calling asnchronous api requests repeatedly until it exceeds specified time.我想重复调用异步 api 请求,直到超过指定时间。 Using async-retry we can only specify retrycount and interval, we wanted to specify even timeout in the parameter.使用 async-retry 我们只能指定重试次数和间隔,我们想在参数中指定甚至超时。 Can you just suggest a way?你能建议一个方法吗?

// 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
});

Here is what you want:这是你想要的:

 const scheduleTrigger = (futureDate) => { const timeMS = new Date(futureDate) - new Date(); return new Promise((res, ref) => { if (timeMS > 0) { setTimeout(() => { res(); }, timeMS); } else { rej(); } }) } //const futureDate = '2020-07-23T20:53:12'; // or const futureDate = new Date(); futureDate.setSeconds(futureDate.getSeconds() + 5); console.log('now'); scheduleTrigger(futureDate).then(_ => { console.log('future date reached'); // start whatever you want stopFlag = false; }).catch(_ => { // the date provided was in the past }); const wait = (ms = 2000) => { return new Promise(res => { setTimeout(_ => { res(); }, ms); }) } const asyncFn = _ => Promise.resolve('foo').then(x => console.log(x)); let stopFlag = true; (async () => { while (stopFlag) { await asyncFn(); await wait(); } })();

So you want to keep retrying for as long as its within a certain timeout?所以你想在一定的超时时间内继续重试吗? How about this:这个怎么样:

// Allow retry until the timer runs out
let retry = true;
const timeout = setTimeout(() => {
  // Set retry to false to disabled retrying
  retry = false;

  // Can also build in a cancel here
}, 10000); // 10 second timeout

const retryingCall = () => {
  apiMethod()
    .then(response => {
      // Optionally clear the timeout
      clearTimeout(timeout);
    })
    .catch(() => {
      // If retry is still true, retry this function again
      if (retry) {
        retryingCall();
      }
    });
};

You can achieve what you want with this function:你可以用这个 function 实现你想要的:

const retryWithTimeout = ({ timeout, ...retryOptions}, apiMethod, callback) => {
  let timedout = false;
  const handle = setTimeout(
    () => (timedout = true, callback(new Error('timeout'))),
    timeout
  );

  return async.retry(
    retryOptions, 
    innerCallback => timedout || apiMethod(innerCallback),
    (err, result) => timedout || (clearTimeout(handle), callback(err, result))
  )
};

It has the advantage of allowing you to use the functionality of async.retry , as you apparently want, and also allows the timeout to take place even when what exceeds the timeout is the apiMethod itself, not the waiting time.它的优点是允许您按照您显然想要的方式使用async.retry的功能,并且还允许超时发生,即使超过超时的是 apiMethod 本身,而不是等待时间。

Usage example:使用示例:

retryWithTimeout( 
  {timeout: 305, times: 4, interval: 100}, 
  (callback) => { callback('some api error'); },
  (err, result) => console.log('result', err, result)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM