2017-09-16 189 views
2

下面是一個簡化我的代碼:如何等待兩個ajax請求完成?

var res = array(); 

$.ajax({ 
    url: 'test1.php', 
    async: true, 
    success: function (data) { 
     res[1] = data.result; 
    } 
}); 

$.ajax({ 
    url: 'test2.php', 
    async: true, 
    success: function (data) { 
     res[2] = data.result; 
    } 
}); 

if (/* both ajax request are done */) { 
    // do stuff 
} else { 
    // wait 
} 

正如你可以看到我用async: true運行在同一時間(並行)那些Ajax請求。現在我需要等待兩個請求完成。我如何確定ajax請求已完成?如果不等到它完成了?

+1

順便說一句,有沒有必要明確地說'異步:TRUE'。這是默認設置。 –

回答

5

您可以使用承諾:

Promise.all([ 
    $.ajax({ url: 'test1.php' }), 
    $.ajax({ url: 'test2.php' }) 
]) 
.then(([res1, res2]) => { 
    // Both requests resolved 
}) 
.catch(error => { 
    // Something went wrong 
}); 
+0

嗯..看起來不錯,upvote。你能告訴我什麼是*承諾*做什麼,我應該什麼時候使用它們? –

+0

@MartinAJ,這可能是有用的https://developers.google.com/web/fundamentals/getting-started/primers/promises。承諾基本上是一個代表未來價值的對象,在這種情況下是一種迴應。 'Promise.all'同時運行promise,'.then'則爲您提供值_iff_成功解決。 – elclanrs

+0

我明白了,謝謝。你爲什麼不在ajax請求中寫'success'塊?我應該寫他們,對吧? –

2

使用Promise.all功能。如果所有的承諾得到解決,並通過將數據作爲陣列的then功能將得到解決,否則將與第一承諾故障值

Promise.all([ 
    $.ajax({ url: 'test1.php'}), 
    $.ajax({ url: 'test2.php'}) 
]) 
.then(results => { 
    // results is an array which contains each promise's resolved value in the call 
}) 
.catch(error => { 
    // The value of the first rejected promise 
}); 
+0

謝謝,upvote –

3

可以使用回調函數,以及被拒絕。

var res = []; 

function addResults(data) { 
    res.push(data); 
    console.log('Request # '+res.length); 
    if (res.length >= 2) { 
     // do stuff 
     console.log('both request has done.'); 
    } else { 
     // wait 
    } 
} 

$.ajax({ 
    url: 'https://jsonplaceholder.typicode.com/posts', 
    success: function (data) { 
     addResults(data); 
    } 
}); 

$.ajax({ 
    url: 'https://jsonplaceholder.typicode.com/posts', 
    success: function (data) { 
     addResults(data); 
    } 
}); 
+0

謝謝。給予好評。不過,我認爲你需要把你的函數放到一個循環中。目前當else {// wait'塊執行時會發生什麼?直到'res.length> = 2'成立爲止,不需要再次調用它? –

0

這個官方文檔可以幫助你。

http://api.jquery.com/ajaxStop/

例如:

var res = []; 
$.ajax({ 
    url: 'test1.php', 
    async: true, 
    success: function (data) { 
     res.push('Ajax one is complete'); 
    } 
}); 

$.ajax({ 
    url: 'test2.php', 
    async: true, 
    success: function (data) { 
     res.push('Ajax two is complete'); 
    } 
}); 
var resALL = function(){ 
    console.log(this) 
} 
//After the requests all complete 
$(document).ajaxStop(resALL.bind(res))