我有一个 ajax 调用可能需要一点时间才能完成。我不想使用 async:false
因为我希望它保持非阻塞代码。所以我决定使用 Q。问题是我不明白如何提取从 Q.when($.ajax...) 返回的 json。我是 Q 的新手。
在此示例中,我希望变量保存从服务器返回的 json:
var res = Q.when($.ajax({
type: "POST",
url: "GetData.asmx/GetMembersList",
contentType: "application/json; charset=utf-8",
dataType: "json"
}));
return res;
最佳答案
对于异步调用,您不能只将结果分配给一个变量,因为该结果要到将来某个时候才会存在。 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
});
然而,promises 的真正力量在于您可以传递它们并在以后使用它们。
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,则不需要使用它,因为 1.5 版 jQuery 会返回一个 deferred object。来自 AJAX 调用。 Deferred 类似于 promise。问offer more power并且 jQuery 的 promises/deferreds 并没有完全实现 Promises/A标准,可能会导致错误处理问题。对于像 AJAX 调用这样简单的事情,如果您已经在使用 jQuery,那么 jQuery promises 通常就足够了。
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
});
关于javascript - 使用 Q,js 进行 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275387/