繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM