使用jQuery Promise,我正在尝试:
我将所有动物声音函数放入数组中,然后调用$.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.');
});
});
}
答案 0 :(得分:1)
$.when()
是少数几个cannot accept an array的jQuery函数之一-您需要将每个promise作为一个单独的参数来调用它:
ES6方式:
$.when(...animalFunctions).then(() => {
$('#txtNotification').text('Done.');
});
石器时代的方式:
$.when.apply($, animalFunctions).then(function () {
$('#txtNotification').text('Done.');
});
答案 1 :(得分:0)
jQuery的Deferred.promise()
允许您“通知”各个项目的进度。
var $def = jQuery.Deferred();
$.ajax({
url: "https://jsonplaceholder.typicode.com/users"
})
.done(function getUsersAsync(users) {
for (var user of users) {
$def.notify(`Fetching comments of ${user.username}, ID: ${user.id}`);
$.ajax({
url: "https://jsonplaceholder.typicode.com/comments",
data: JSON.stringify({ id: user.id })
})
.done(function (arg) {
// Do stuff with the comments here
});
}
$def.resolve(users.length);
})
.fail(function () {
$def.reject('ERR: Failed retrieving comments');
});
$def
.progress(function (message) {
console.log(message);
})
.done(function (count) {
console.log('ALL DONE. Total user: ' + count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 2 :(得分:-3)
将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.');
});
});
}