为什么我的jQuery Promise立即解决?

时间:2019-02-08 01:52:16

标签: jquery ajax promise

使用jQuery Promise,我正在尝试:

  1. 为所有可能的值(动物)调用API
  2. 为每种动物(动物的声音)调用API方法
  3. 通知每只动物的声音何时回来-假设需要一段时间才能解决
  4. 在所有动物声音返回时通​​知

我将所有动物声音函数放入数组中,然后调用$.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.');
    });
  });
}

3 个答案:

答案 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.');
                });
            });
    }