当两个Ajax请求完成时,做callback最简单的方法

我有一个作为API的Node.js应用程序。 我得到一个请求,基于这个动作,我向另一个服务器执行一些ajax请求,caching结果,并把结果发送回客户端。

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

另外,这些ajax请求是棘手的,就像有时候服务器使用我们的方式,或者给出不好的结果,在这种情况下,我recursion地做同样的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 }); 

带有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本身的一部分,它应该检查callback中err是否为空,如果是,则重试一次或两次(取决于您期望的行为)。