延迟与jQuery - when()与getJSON()回调

Deferred with jQuery - when() with getJSON() callbacks

本文关键字:回调 getJSON when jQuery 延迟      更新时间:2023-09-26

我正在尝试理解jQuery中的when函数和延迟对象。

$.when($.getJSON('/echo/json', function () {
    console.log('sucess');
}, function () {
    console.log('error');
})).then(console.log('get JSON ready!'));

这个例子返回:

get JSON ready!
sucess

…但是我想要实现成功,回调首先触发:

sucess
get JSON ready!

我该怎么做呢?

http://jsfiddle.net/lukaszr/rBFmL/

您忘记了函数包装-您的代码立即调用console.log而不是传递回调函数:

.then(console.log('get JSON ready!'));
应:

.then(function() {
    console.log('get JSON ready!');
});

小提琴

尝试使用.done(…),而不是犹豫(…)。jQuery文档中有一些示例。

http://api.jquery.com/jQuery.when/