2017-09-16 184 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))