我有一个充当 API 的 Node.js 应用程序。我收到一个请求,基于我向另一台服务器执行一些 ajax 请求的操作,缓存结果,然后将结果发送回客户端。
现在,对于这个新请求,我需要执行两个单独的 ajax 调用,并在两个调用完成后向客户端做出响应。为了加快速度,如果可能的话,我不想嵌套它们。
此外,这些 ajax 请求很棘手,有时服务器会对我们的时间进行计时,或者返回错误的结果,在这种情况下,我会递归地执行相同的 ajax 请求。
最佳答案
好吧, 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
});
带有 Promise 的 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 是否不为 null,如果是,则重试一次或两次(取决于您想要的行为)。
关于ajax - 两个ajax请求完成时执行回调的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035296/