Soo*_*ead 3 javascript asynchronous node.js promise
使用node.js,我希望http.get以一次仅运行 10 个(或 n 个)的方式访问多个远程 url。
如果本地发生异常(m 次),我还想重试请求,但当状态代码返回错误(5XX、4XX 等)时,请求将被视为有效。
这对我来说真的很难理解。
问题:
似乎对于每个异步问题都建议使用 Promise,但我最终嵌套了太多 Promise,它很快就变得无法编码。
有很多方法可以处理同时运行的 10 个请求。
异步库- 使用异步库的方法.parallelLimit() 可以指定一次要运行的请求数。
Bluebird Promise Library - 使用Bluebird Promise 库并将request您的库包装http.get()到可以返回 Promise 的内容中,然后Promise.map()与设置为 的并发选项一起使用10。
手动编码- 手动编码您的请求以启动 10 个请求,然后每次完成一个请求时启动另一个请求。
在所有情况下,您都必须手动编写一些重试代码,并且与所有重试代码一样,您必须非常仔细地决定重试哪些类型的错误、重试的时间、重试尝试之间的退避程度以及何时重试。最终放弃(所有你没有指定的事情)。
其他相关回答:
我首选的方法是使用 Bluebird 和 Promise。包括按顺序重试和结果收集,可能如下所示:
const request = require('request');
const Promise = require('bluebird');
const get = Promise.promisify(request.get);
let remoteUrls = [...]; // large array of URLs
const maxRetryCnt = 3;
const retryDelay = 500;
Promise.map(remoteUrls, function(url) {
let retryCnt = 0;
function run() {
return get(url).then(function(result) {
// do whatever you want with the result here
return result;
}).catch(function(err) {
// decide what your retry strategy is here
// catch all errors here so other URLs continue to execute
if (err is of retry type && retryCnt < maxRetryCnt) {
++retryCnt;
// try again after a short delay
// chain onto previous promise so Promise.map() is still
// respecting our concurrency value
return Promise.delay(retryDelay).then(run);
}
// make value be null if no retries succeeded
return null;
});
}
return run();
}, {concurrency: 10}).then(function(allResults) {
// everything done here and allResults contains results with null for err URLs
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2137 次 |
| 最近记录: |