jquery $.when().done() 是否等待所有 $.ajax().done() 完成?



我对承诺很陌生,并试图确保我有正确的方法。我的问题是,当将$.when$.ajax调用列表一起使用时,$.when.done是否等到所有$.ajax调用的所有.done完成后执行?也许这个代码片段将有助于解释这个问题:

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>

最新更新