jQuery承诺与getJSON和回调

jQuery承诺与getJSON和回调,jquery,getjson,jquery-deferred,promise,Jquery,Getjson,Jquery Deferred,Promise,我有一个带有回调的ajax调用。我想在回调结束后调用另一个方法。我使用了jQuery中的promise API,但正如您在下面看到的,第二个方法是在第一个方法完成之前调用的 有什么想法吗 my.data = function () { var loadFlights = function (callback) { //$.getJSON("/api/Acceptance/", function (data) { // callback(data

我有一个带有回调的ajax调用。我想在回调结束后调用另一个方法。我使用了jQuery中的promise API,但正如您在下面看到的,第二个方法是在第一个方法完成之前调用的

有什么想法吗

  my.data = function () {
     var loadFlights = function (callback) {
        //$.getJSON("/api/Acceptance/", function (data) {
        //    callback(data);
        //}); 
        $.getJSON("/api/Acceptance").success(function (data) {
           console.log("first: " + new Date().getTime());
           callback(data); 
        })
        .then(console.log("second:" + new Date().getTime()));
     };

     return { load: loadFlights }
  }();
控制台的结果:

second:1357393615115 
first: 1357393615246 

您没有向
.then()
提供回调函数,而是传入
控制台.log(“second:“+new Date().getTime())
(这就是为什么
second
会立即打印的原因)

创建一个匿名函数,用于包装要调用的代码(就像在
.success()
中所做的那样):

演示:

试试这个:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});
参考:

最好的答案,因为输出的毫秒数使它非常清晰,但这是函数和返回值的内部值吗?
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});