首页 > 解决方案 > 排队异步请求

问题描述

我正在尝试设置一个排队系统,以便发布请求重复n多次,间隔为i. 理想情况下,我想把这一切都包装在一个单一的承诺中,所以整个事情可以是异步的。

到目前为止,我有这个,感觉有点混乱和hacky。我觉得我可能错过了一个更简单的解决方案,但我似乎找不到任何东西:

// this is mocked to avoid a wall of code
const postData = (url, data) => Promise.resolve(true);

// this is mocked to avoid a wall of code
const resIsFailed = () => true;

const requestChain = ({
  url,
  data,
  maxRequests,
  requestTimeout,
  currentRequest = 0,
  requestIncrement = increment => increment,
}) => {

  // exit condition
  if (currentRequest >= maxRequests || (!maxRequests)) {
    console.log('Too many failed requests');
    return Promise.reject(new Error('Too many attempts'));
  }

  // post the data, if it fails, try again
  postData(
    url,
    data,
  ).then(res => {
  
    if (resIsFailed(res)) {
    
      console.log('Failed response: ');
      console.dir(res);
      
      setTimeout(() => {
        requestChain({
          url,
          data,
          maxRequests,
          requestTimeout: requestIncrement(requestTimeout),
          currentRequest: currentRequest + 1,
          requestIncrement,
        });
      }, requestTimeout);
      
    } else {
    
      return Promise.resolve(res);
      
    }
  });
}

requestChain({
  url: 'fail',
  data: {},
  maxRequests: 5,
  requestTimeout: 100,
})

标签: javascriptpromise

解决方案


异步库对于控制所有类型的异步链接等非常有帮助。您可能想看看async.retry。它应该给你确切的行为。


推荐阅读