请参阅jsFiddle:https://jsfiddle.net/dtds1n2t/2/¸
这是来自jsFiddle的代码:
var resultData = "result-data-string";
// Create a jQuery deferred
defA = $.Deferred();
// Make an ajax call, which creates a jqXHR object
defB = $.ajax({
type: "POST",
url: "/echo/json/",
data: {
json: JSON.stringify(resultData),
delay: 1.5
}
});
defA.done(function(data) {
console.log("defA resolved");
console.log(data);
// data is resultData, as expected
});
defB.done(function(data) {
console.log("defB resolved");
console.log(data);
// data is resultData, as expected
});
defAB = $.when(defA, defB);
defAB.done(function(aData, bData) {
console.log("defAB resolved");
console.log(aData);
// aData is resultData, as expected
console.log(bData);
// bData is an array for some reason:
// [ resultData, "success", jqXHR object?
});
defA.resolve(resultData);
这是控制台输出:
defA resolved
result-data-string
defB resolved
result-data-string
defAB resolved
result-data-string
["result-data-string", "success", Object]
为什么bData在数组中的$ .when()。done回调部分?
我的defA和defB可以是来自$ .ajax()调用的jqXHR对象,也可以是$ .Deferred()。promise()对象。我希望$ .when()。done回调以相同的格式接收数据,无论底层的promise / Deferred对象是如何创建的!