完成两个ajax请求后执行回调的最简单方法
我有一个充当API的Node.js应用程序.我收到一个请求,该请求基于我对另一台服务器执行一些ajax请求,缓存结果并将结果发送回客户端的操作.
I have a Node.js application that functions as an API. I get a request, based on the action I perform some ajax request to another server, cache the results, and send the results back to the client.
现在对于这个新请求,我需要执行两个单独的ajax调用,并在两个都完成时向客户端做出响应.为了加快处理速度,我不想将它们嵌套.
Now for this new request I need to do two separate ajax calls, and give a response to the client when both of them are finished. To speed things up I do not want to nest them if that is possible.
此外,这些ajax请求非常棘手,有时服务器会浪费我们的时间,或者返回不好的结果,在这种情况下,我递归地执行相同的ajax请求.
Also, these ajax request are tricky, in the way that sometimes the server times our, or give bad results back, in that case I recursively do the same ajax request.
好的,诺言使这个琐碎的事情变得如此:
Well, promises make this trivial:
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
的示例可以是:
An example of getWithRetry
with promises can be something like:
function getWithRetry(url){
return http.getAsync(url).catch(function(err){
return http.getAsync(url); // in real code, check the error.
});
}
但是,您没有使用它们,因此必须手动进行同步.
However, you're not using them, so you have to manually synchronize it.
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
在回调中是否为null,如果是,则重试一次或两次(取决于您的期望行为).
As for retrying, that can be a part of requestWithRetry
itself, which should just check if err
is not null in the callback, and if it is, retry once or twice (depending on your desired behavior).