两个ajax请求完成后进行回调的最简单方法

时间:2014-04-12 19:46:14

标签: ajax node.js

我有一个用作API的Node.js应用程序。我收到一个请求,根据我对另一台服务器执行一些ajax请求的操作,缓存结果,然后将结果发送回客户端。

现在对于这个新请求,我需要做两个单独的ajax调用,并在两个调用完成后给客户端做出响应。为了加快速度,如果可能的话,我不想嵌套它们。

此外,这些ajax请求很棘手,有时服务器会将我们的时间计算在内,或者给出错误的结果,在这种情况下,我递归地执行相同的ajax请求。

1 个答案:

答案 0 :(得分:1)

嗯,承诺使这个变得微不足道:

 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是否为空,如果是,则重试一次或两次(取决于你的期望的行为)。