javascript - 排队异步请求
问题描述
我正在尝试设置一个排队系统,以便发布请求重复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,
})
解决方案
异步库对于控制所有类型的异步链接等非常有帮助。您可能想看看async.retry。它应该给你确切的行为。
推荐阅读
- ios - 比较单元测试中的 swift Type 值 - XCTAssertEqual vs ==
- flutter - 如何在颤动的同一个小部件中同时使用 pageStoragekey 和 uniqueKey?
- batch-file - 如何使用批处理文件解压缩具有动态名称的文件?
- swift - 由于“NSInternalInconsistencyException”错误而终止应用程序
- azure - Azure Monitor 与 Kubernetes 入口控制器的集成
- python - TypeError:无法使用 RQ 腌制“_thread.lock”对象
- visual-studio - 如何在 mac 机器上降级 Xamarin.ios?
- node.js - Bot 框架中的上下文管理 - Node JS
- package - snmpd 没有发现问题?
- xamarin.forms - FFImageLoading 下载后显示图片