使用异步调用,您不能只将结果分配给变量,因为该结果要到将来某个时候才会存在。 Q.when 不返回结果,它返回一个 promise 对象,该对象最终会得到一个结果。
如果您只想对 JSON 做一件事,您只需内联 .then 调用即可获得结果。
Q($.ajax({
type: "POST",
url: "GetData.asmx/GetMembersList",
contentType: "application/json; charset=utf-8",
dataType: "json"
})).then(function (res) {
// res now contains the JSON
});
然而,Promise 的真正威力在于您可以传递它们并在以后使用它们。
function getMembersList() {
return Q($.ajax({
type: "POST",
url: "GetData.asmx/GetMembersList",
contentType: "application/json; charset=utf-8",
dataType: "json"
}));
}
var membersList = getMembersList();
membersList.then(function (res) {
// once the AJAX call completes this will
// run. Inside this function res contains the JSON
return res; // pass res to the next chained .then()
}).then(function (res) {
// you could chain another then handler here
});
// do some other stuff
membersList.then(function (res) {
// you could also add another then handler later too
// even long after the AJAX request resolved and this
// will be called immediately since the promise has already
// resolved and receive the JSON just like the other
// then handlers.
});
如果您没有其他原因使用 Q,则不需要使用 Q,因为 1.5 版 jQuery 从 AJAX 调用返回 deferred object。 Deferred 类似于 Promise。 Q 确实 offer more power 和 jQuery 的 promises/deferreds 并没有完全实现 Promises/A 标准,可能会导致错误处理问题。对于像 AJAX 调用这样简单的事情,如果您已经在使用 jQuery,那么 jQuery 承诺通常就足够了。
var membersList = $.ajax({
type: "POST",
url: "GetData.asmx/GetMembersList",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
membersList.then(function (res) {
// res now contains the JSON
});