好吧,promise 让这变得微不足道:
var http = Promise.promisifyAll(require("http"));
Promise.all(["url1","url2"]).map(getWithRetry).spread(function(res1,res2){
// both responses available
}).catch(function(err){
// error handling code
});
带有承诺的getWithRetry 的示例可能类似于:
function getWithRetry(url){
return http.getAsync(url).catch(function(err){
return http.getAsync(url); // in real code, check the error.
});
}
但是,你没有使用它们,所以你必须手动同步它。
var res1,res2,done = 0;;
requestWithRetry("url1",function(err,result){
if(err) handleBoth(err,null,null);
res1 = result;
done++;
if(done === 2) handleBoth(null,res1,res2);
});
requestWithRetry("url2",function(err,result){
if(err) handleBoth(err,null,null);
res2 = result;
done++;
if(done === 2) handleBoth(null,res1,res2);
});
function handleBoth(err,res1,res2){
// both responses available here, the error too if an error occurred.
}
至于重试,它可以是requestWithRetry 本身的一部分,它应该只检查err 在回调中是否不为空,如果是,则重试一次或两次(取决于您想要的行为)。