2017-09-24 19 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 –