【发布时间】:2016-02-16 05:37:12
【问题描述】:
我一直在搜索和尝试这么多变体,但没有运气。
我有一组用户:
var arr = ['tom', 'sally', 'jill', 'sam', 'john'];
我想使用 $.ajax 将这些用户传递到 2 个 API(相同的站点、不同的 URL、用于不同的数据集):
function getStatus1() {
return $.each(arr, function (index, value) {
arrStatus.push($.ajax({
url: 'https://some/url',
dataType: 'json'
})
.always(function (response) {
console.log('from getStatus1');
}));
});
}
function getStatus2() {
return $.each(arr, function (index, value) {
arrStatus.push($.ajax({
url: 'https://some/url',
dataType: 'json'
})
.always(function (response) {
console.log('from getStatus2');
}));
});
}
$.when(getStatus1(), getStatus2()).then(function () {
console.log('after getStatuses');
});
无论我尝试什么,我总是先得到“getStatuses”,我认为这是因为我没有在我的函数中返回承诺......但我不知道为什么会这样!
这篇文章是我最接近我的情况,但它不涉及使用 $.each 或数组... :( jQuery Promise then not working after AJAX
我非常感谢任何人都可以解决我的问题。
谢谢!
编辑 这是一个 Plnkr 来展示我的 ajax 问题: https://plnkr.co/edit/jRAAjXX4zFprUbx1KPlN?p=preview
感谢大家的回复,我真的希望有一个解决方案!
【问题讨论】:
-
在成功的ajax响应回调里面尝试push到数组怎么样?
-
你的 when...then 正在工作,但 ithink 在你的 ajax 调用中存在问题
-
我也试过了:function getDetails() { return $.each(arr, function (index, value) { arrDetails.push($.ajax({ url: 'some/url' + value, dataType: 'json', 成功: function (response) { console.log('from getDetails'); } })); }); } ...给出相同的结果:(
-
$.each没有返回值...
标签: javascript jquery arrays ajax asynchronous