使用getJSON和回调的jQuery承诺

时间:2013-01-05 13:51:21

标签: jquery getjson jquery-deferred promise

我有一个带回调的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 

2 个答案:

答案 0 :(得分:13)

而不是向.then()提供回调函数,而是传递console.log("second:" + new Date().getTime())的输出(这就是为什么second会立即打印出来的原因。)

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

$.getJSON("/echo/json").success(function(data) {
  console.log("first: " + new Date().getTime());
}).then(function() {
  console.log("second:" + new Date().getTime())
});

演示:http://jsfiddle.net/Blender/fJb7h/

答案 1 :(得分:0)

尝试一下:

// 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" );
});

参考: https://api.jquery.com/jquery.getjson/

相关问题