[英]Does jquery $.when().done() wait for all $.ajax().done()'s to complete?
我對諾言很陌生,並且正在嘗試確保我采用正確的方法。 我的問題是,當使用$.when
用列表$.ajax
調用,並在.done
中的$.when
等待執行,直到所有的.done
“所有第$.ajax
調用完成了嗎? 也許這段代碼片段可以幫助解釋這個問題:
var apiSoftFail = false;
var myCallback = function(jsonData) {
// lets say the json data returned by the ajax call contains a boolean
// indicator of whether or not the purpose for doing the api call was successful
if (jsonData.success) {
// do things with the jsonData returned
} else {
apiSoftFail = true;
}
};
var apiRequest = function(endpoint,callback) {
return $.ajax(
{'url':endpoint,'contentType': 'application/json'}
).done(function(data) {
callback(data)
});
};
$.when(
apiRequest("/apiEndpoint1",myCallback),
apiRequest("/apiEndpoint2",myCallback),
apiRequest("/apiEndpoint3",myCallback)
).done(function() {
if (apiSoftFail) {
// "API Soft Fail"
doThisFailureFunction();
} else {
doThisSuccessFunction();
}
}).fail(function() {
// "API Hard Fail"
doThisFailureFunction();
});
在此先感謝您提供的任何見解或建議,以獲取更好的方法。
是的,您的代碼僅有一些問題。 特別是,您需要賦予done
功能。
.done(function() {
if (apiSoftFail) {
// "API Soft Fail"
doThisFailureFunction();
} else {
doThisSuccessFunction();
}
}
您可以在此處檢查:api調用都將首先調用它們自己的回調並輸出其結果,然后將打印“成功”。
如果您多次運行此代碼段,則會看到各個請求未按定義的順序運行(某些請求有時會在其他請求之前完成),但是“成功”打印始終會排在最后。
var apiSoftFail = false; var myCallback = function(jsonData) { // lets say the json data returned by the ajax call contains a boolean // indicator of whether or not the purpose for doing the api call was successful if (jsonData) { console.log(jsonData); // do things with the jsonData returned } else { apiSoftFail = true; } }; var doThisFailureFunction = function() { } var doThisSuccessFunction = function() { console.log("success"); } var apiRequest = function(endpoint,callback) { return $.ajax( {url:endpoint,'contentType': 'application/json'} ).done(function(data) { callback(data); }); }; $.when( apiRequest("https://jsonplaceholder.typicode.com/todos/1",myCallback), apiRequest("https://jsonplaceholder.typicode.com/todos/2",myCallback), apiRequest("https://jsonplaceholder.typicode.com/todos/3",myCallback) ).done(function() { if (apiSoftFail) { // "API Soft Fail" doThisFailureFunction(); } else { doThisSuccessFunction(); } }).fail( // "API Hard Fail" doThisFailureFunction );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.