[英]Using Q,js for ajax calls
我有一個可能需要一些完成的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
});
然而,承諾的真正力量來自於你可以傳遞它們並在以后使用它們。
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從AJAX調用返回延遲對象 。 延期類似於承諾。 Q確實提供了更多功能,而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
});
以下是有關使用jQuery ajax的q文檔中的一些示例。
return Q(jQuery.ajax({
url: "foobar.html",
type: "GET"
})).then(function (data) {
// on success
}, function (xhr) {
// on failure
});
// Similar to jQuery's "complete" callback: return "xhr" regardless of success or failure
return Q.promise(function (resolve) {
jQuery.ajax({
url: "foobar.html",
type: "GET"
}).then(function (data, textStatus, jqXHR) {
delete jqXHR.then; // treat xhr as a non-promise
resolve(jqXHR);
}, function (jqXHR, textStatus, errorThrown) {
delete jqXHR.then; // treat xhr as a non-promise
resolve(jqXHR);
});
});
https://github.com/kriskowal/q/wiki/Coming-from-jQuery
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.