为什么我的jQuery承诺会立即得到解决?
使用jQuery承诺,我试图:为什么我的jQuery承诺会立即得到解决?,jquery,ajax,promise,Jquery,Ajax,Promise,使用jQuery承诺,我试图: 为(动物的)所有可能的值调用API 为每种动物调用API方法(动物声音) 当每一个动物的声音回来时通知——比如说,这需要一段时间才能解决 返回所有动物声音时通知 我将所有动物声音函数放入一个数组中,然后调用$.when()。我希望当所有动物的声音都返回时,这个问题会得到解决,但我发现它会立即得到解决。有人知道我做错了什么吗 function () { $('#txtNotification').text('Started ....'); $.ajax({
$.when()
。我希望当所有动物的声音都返回时,这个问题会得到解决,但我发现它会立即得到解决。有人知道我做错了什么吗
function () {
$('#txtNotification').text('Started ....');
$.ajax({
url: "/api/animals/all"
}).done(function(data) {
var animalFunctions = [];
for (var animalType of data) {
var animalFunction = $.ajax({
url: "/api/animal/sound/" + animalType
}).done(function(data) {
$('#txtNotification').text(data);
});
animalFunctions.push(animalFunction);
}
$.when(animalFunctions).then(function() {
$('#txtNotification').text('Done.');
});
});
}
将
return:false
添加到传递给.done()的anon函数中。看看这是否有帮助
function () {
$('#txtNotification').text('Started ....');
$.ajax({
url: "/api/animals/all"
})
.done(function( data ) {
var animalFunctions = [];
for (var animalType of data) {
var animalFunction = $.ajax({
url: "/api/animal/sound/" + animalType
})
.done(function(data) {
$('#txtNotification').text(data);
return false;
}
);
animalFunctions.push(animalFunction);
}
$.when(animalFunctions).then(function() {
$('#txtNotification').text('Done.');
});
});
}
是为数不多的jQuery函数之一,您需要将每个承诺作为单独的参数调用它:
ES6方式:
$.when(...animalFunctions).then(() => {
$('#txtNotification').text('Done.');
});
$.when.apply($, animalFunctions).then(function () {
$('#txtNotification').text('Done.');
});
石器时代的方式:
$.when(...animalFunctions).then(() => {
$('#txtNotification').text('Done.');
});
$.when.apply($, animalFunctions).then(function () {
$('#txtNotification').text('Done.');
});
jQuery允许您“通知”单个项目的进度
var$def=jQuery.Deferred();
$.ajax({
url:“https://jsonplaceholder.typicode.com/users"
})
.done(函数getUsersAsync(用户){
for(用户的var用户){
$def.notify(`Fetching comments of${user.username},ID:${user.ID}`);
$.ajax({
url:“https://jsonplaceholder.typicode.com/comments",
数据:JSON.stringify({id:user.id})
})
.done(函数(arg){
//在这里做一些评论
});
}
$def.resolve(用户长度);
})
.fail(函数(){
$def.reject('错误:检索注释失败');
});
$def
.进度(功能(消息){
控制台日志(消息);
})
.完成(功能(计数){
console.log('ALL DONE.Total user:'+count);
});代码>
感谢您的回复。但这并不管用。Cheers是添加到@MTCoster注释的为数不多的jQuery函数之一,请尝试将$当(animalFunctions)
更改为$。当(…animalFunctions)
。扩展运算符(…
)可以将数组转换为参数列表。这是我的建议。ES6之前的解决方案应该是$.when.apply($,animalFunctions)
@MTCoster。明亮的这很有效。我永远不会得到那个。如果你把它写下来作为答案,我会投票接受。谢谢你的帮助