我有一个充当API的Node.js应用程序。我收到一个请求,该请求基于我对另一个服务器执行一些ajax请求,缓存结果并将结果发送回客户端的操作。
现在,对于这个新请求,我需要执行两个单独的ajax调用,并在两个请求都完成时给客户端一个响应。为了加快速度,如果可能的话,我不想嵌套它们。
而且,这些ajax请求是棘手的,有时服务器会将我们的ajax请求计时,或者返回不好的结果,在这种情况下,我递归地执行相同的ajax请求。
好吧,诺言使这变得微不足道:
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
with promises的示例可以是:
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
回调中的not是否为null,如果是,则重试一次或两次(取决于您的期望行为)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句