jQuery延迟不与getJSON调用异步执行

时间:2016-09-02 13:12:22

标签: javascript jquery

我的问题是b()最后执行,但它应该是第二顺序。我想在每次点击一个按钮时调用一个JSON api(并且总是发送新的api调用),但它应该从div中删除最后一个api消息:

$(document).ready(function() {

  function test() {

    function a() {
      $("#message-quote, #message-person").empty();
      console.log('p1');
    };

    function b() {
      console.log('p2 - before getJSON');
      $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
        $("#message-quote").append(a[0].content)
        $("#message-person").append("<p>— " + a[0].title + "</p>")
        console.log('p2 - in getJSON');
      });
    };

    function c() {
      $("body, .button, .quote-icons a").css("background-color", "red");
      $(".quote-text").css("color", "red");
      console.log('p3');
    };

    var d = $.Deferred(),
    p = d.promise();
    p.then(a()).then(b()).then(c());
    d.resolve();
  };

  $("#getMessage").on("click", function() {
    test();
  });

});

我收到的订单是:

"p1"
"p2 - before getJSON"
"p3"
"p2 - in getJSON"

1 个答案:

答案 0 :(得分:1)

你不等待b()的返回,你需要链接承诺,因为它以异步方式调用。

如果你从b()返回一个promise,它应该等待getJSON的结果在它继续之前返回。

此外,您的函数正在立即执行,.then(callback)需要执行一个稍后可以执行的函数,而不是直接执行函数

function b() {

      return $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
        $("#message-quote").append(a[0].content)
        $("#message-person").append("<p>— " + a[0].title + "</p>")
        console.log('p2');
        // resolve the promise, the call has been completed
      });
    };

 var d = $.Deferred(),
    p = d.promise();
    p.then(a)
     .then(b)
     //the context of .then will now be the promise out of b()
     .then(c);
    d.resolve();

注意:还需要从其他方法返回Promise。

编辑:正如Rocket指出的那样,jQuery Ajax调用实现了promise方法

工作示例:https://jsfiddle.net/rsfxpg38/4/

你可以从这篇文章中看到它的一个例子:  How do I chain a sequence of deferred functions in jQuery 1.8.x?

相关问题