【发布时间】:2016-09-02 13:12:21
【问题描述】:
我的问题是 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"
【问题讨论】:
-
您确定
b()是最后运行的吗?您是基于控制台输出的断言吗?因为 a()-b()-c() 将给你输出 p1-p3-p2。如果您删除承诺并调用a();b();c(),您将得到“p1 p3 p2”。通过在$.getJSON之前添加console.log来确认这一点。 -
我更新了我的问题。
-
在
b()添加回车,即:return $.getJSON(... -
问题:你明白为什么它是这样排列的吗?你正试图让它与
.then()一起工作?
标签: javascript jquery