2017-09-24 71 views
0

这里是我的代码:如何确定所有的ajax请求已解决?

function ajaxRequest(value, path, website){ 
    var status = false; 
    return new Promise(function (resolve, reject) { 
     window[website] = $.ajax({ 
      url : path, 
      type : 'GET', 
      data: { "name": value, 
        "_token": $('meta[name="_token"]').attr('content') 
      }, 

      beforeSend: function(){ 
       if(window[website] != null) { 
        window[website].abort(); 
       } 
      }, 
      success: function (people) { 
       status = true; 
       resolve([status, people]); 
      }, 

      error: function (jqXHR, textStatus, errorThrown) { 
       reject([status, textStatus]); 

      }, 

      timeout: 20000 

     }); 
    }); 
} 

我这样调用该函数:

ajaxRequest('Jack', 'search/twitter', 'twitter').then(function(res) { console.log(res)}, function(err){console.log(err)}); 
ajaxRequest('Jack', 'search/instagram', 'instagram').then(function(res) { console.log(res)}, function(err){console.log(err)}); 

现在我需要知道这两个Ajax请求完成。我怎样才能做到这一点?

注意到我认为我必须使用promise.all(),但不知道如何在我的情况下使用它。

+0

你可以通过函数调用'$。当()' – guest271314

+0

@ guest271314 EMM,不知道你意味着什么,你有什么请举例吗? –

回答

2

你是对的,promise.all()是为了解决这个问题而发明的。 它只是返回一个新的承诺,将解决当所有给定的承诺解决。

在你的情况,你可以用Promise.all类似的东西包住2个Ajax调用:

promise.all([ 
    ajaxRequest('Jack', 'search/twitter', 'twitter').then(function(res) { console.log(res)}, function(err){console.log(err)}), 
    ajaxRequest('Jack', 'search/instagram', 'instagram').then(function(res) { console.log(res)}, function(err){console.log(err)}) 
]).then(([response1, response2]) => { 
    // Here you execute your logic when both of the promises are resolved. 
}) 
+0

在你的代码中,我实际上调用了这个函数两次。一次通常*(在我的代码中)*,一次放入'promise.all()'*(在您的代码中)* –

+0

我忘了提及您需要用'Promise.all'包装您的2次调用在我的代码中。 – felixmosh

+0

嗯,我需要单独获取这些ajax请求的结果,而不是在完成所有工作时完成。 –

1

你可以通过函数调用来$.when()。注意,jQuery.ajax()返回一个jQuery承诺对象,使用Promise构造函数是没有必要的

$.when(ajaxRequest(), ajaxRequest()) 
.then(function(...results) { 
    // do stuff with `results` array 
}) 
.fail(function(jqxhr, textStatus, errorThrown) { 
    console.error(errorThrown) 
}) 
+0

嗯,我需要分别得到这些ajax请求的结果*(异步)*,而不是在完成所有操作的同时。我只需要知道所有这些都是为了阻止闪烁放大镜。 –

+0

请参阅['。.when()'](http://api.jquery.com/jquery.when/)。在每个异步或同步调用返回值之前,不应调用链接.then()。如果任何'.ajax()'调用被拒绝或者抛出错误,'.fail()'会被触发。 – guest271314

+0

我会尝试一下,谢谢,upvote –