【问题标题】:Queuing Async Requests排队异步请求
【发布时间】:2018-08-20 21:10:38
【问题描述】:

我正在尝试设置一个排队系统,以便以i 的间隔重复发布请求n 次。理想情况下,我想将这一切包装在一个 Promise 中,这样整个事情就可以是异步的。

到目前为止,我有这个,感觉有点混乱和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,
})

【问题讨论】:

  • 签出async/await
  • 你应该承诺 setTimeout 并正确链接承诺,否则这看起来不错
  • 你到底觉得什么地方看起来很乱?
  • @Bergi 我认为您对需要承诺的setTimout 是正确的。我目前正在努力将其切换为async/await,因为我认为它看起来会更好
  • @OliverRadini,除了承诺setTimeout,你还可以将return Promise.resolve(res);简化为return res;。从 then 回调中,您可以返回一个值;它不需要被承诺包装。

标签: javascript promise


【解决方案1】:

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

【讨论】:

  • 谢谢,我看看这个
  • async.js 库是基于回调的,在处理 promise 代码时超级没用。
  • @Bergi 你说得对。尽管如此,它解决了问题。如果您仍然需要返回一个承诺,只需创建一个并在 async.retry 的回调中解决/拒绝它。
  • @MoritzHerbert 这将比 OP 目前拥有的更丑陋(并且容易出错)。另外async.retry 似乎不支持requestIncrement
猜你喜欢
  • 1970-01-01
  • 2017-11-23
  • 2014-10-06
  • 2019-10-03
  • 2019-11-05
  • 2019-02-14
  • 2011-06-16
  • 2014-10-18
  • 1970-01-01
相关资源
最近更新 更多