为什么推迟的'然后'在嵌套的AJAX成功回调之前触发回调?

时间:2016-02-05 01:49:00

标签: javascript jquery ajax promise jquery-deferred

我是jQuery承诺的新手,而且我无法成功地做我认为的事情。我将一个AJAX请求传递到when。在该请求的成功回调中,我创建了一个第二个 AJAX请求,并将返回的promise分配给我传递给我从成功回调返回的when的变量。 Here is a fiddle of the below code.

Item = function(data) {
    this.name = data.name;
    this.price = data.price;
    this.cost = data.cost;
}

$(function() {

  var rec = new Item({
    name: '',
    price: 0,
    cost: 0
  });

    $.when($.ajax({
      url: '/echo/json',
      //url: '/error',
      success: function() {

        rec.name = 'Item1';

        // Get price
        var p1 = $.ajax({
            url: '/echo/json',
          success: function() {
            rec.price = 999.99; // I expect to see the price rendered as 999.99
          }
        });

        return $.when(p1);

      },
      error: function() {

        rec.name = 'NULL';

      }
    })
  ).then(function() {
        $('#resultText').css('color', 'green').append('ITEM UPDATE SUCCESS');
        $('#name').text(rec.name);
        $('#price').text(rec.price);
      $('#cost').text(rec.cost);
  }, function() {
        $('#resultText').css('color', 'red').append('ITEM UPDATE FAILURE');
        $('#price').text(rec.price);
      $('#cost').text(rec.cost);
  });
})

当你操作小提琴时,我不明白为什么渲染的价格"不是999.99。为什么p1在成功回调运行之前解析?需要改变什么以使其符合我的期望?

1 个答案:

答案 0 :(得分:2)

你的承诺链是一团糟,你的意图远非清晰,所以这是一个基于你的代码松散的例子,以展示你如何让事情变得更容易理解。

$.ajax({url: '/echo/json'}) //do one request
    .then(function(resultFromServer){
            //yay! 1st request was successful
            return $.ajax({url: '/echo/json'}); //then do another request
        },function(err){
            //something went wrong with the AJAX

            //rethrow to let the next "catch" pick this up, skipping further "then" clauses
            throw err;
        })
    .then(function(resultFromServer) {
            rec.price=999.99; //yay! success again
            //...
        },function() {
            //something went wrong
        });