2016-02-05 50 views
1

我是新来的jQuery承诺,我无法成功地做我认为是可能的。我有一个单一的AJAX请求传入when。内部的请求的成功回调,我做一个 AJAX请求,并指定返回的承诺,我传递给when,我从成功回调返回一个变量。 Here is a fiddle of the below code.为什么在嵌套AJAX的成功回调之前触发延迟的'then'回调?

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在成功回调运行之前解析?为了达到我的期望,需要改变什么?

+2

外承诺不关心'success'回调的返回值,所以它完成,然后移动到它的'when'而不关心的是第二个请求已经取得进展。你应该在第二个AJAX调用中附加一个附加的'then'事件。 –

+0

代码中不需要'$ .when'。你应该删除'$ .when'的每一个实例。 – meagar

+0

仅供参考,[这里是如何做到工作AJAX的小提琴(https://jsfiddle.net/0hdonu6e/13/)。 –

回答

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 
     }); 
+0

是的,我想我是在迷惑自己。我也有考虑复杂一点的情况下,我没有最初建立到我的小提琴......我在这里更新它:https://jsfiddle.net/0hdonu6e/7/,它似乎是在做什么,我期望。谢谢您的帮助。 – Thelonias

+0

@Ryan如果这解决了您的问题,请将此答案标记为已接受 –