javascript - jQuery .done 未按预期返回

标签 javascript jquery ajax promise

我知道这是我的误解,我正在努力了解我做错了什么,我真的需要一些帮助。

我有一个 ajax 请求,该请求成功并返回数据正常。 Api 返回一个错误代码,然后我尝试根据给定的代码返回响应,但该函数仅返回 ajax 调用传递的内容。

function getData(){
    var promise = $.ajax({
       url: 'api.php',
       type: 'POST',
       dataType: 'json'
    });
    return promise.done(function(data){
        console.log(data);
        if(data.errorCode === 0){
            return data;
        } else {
            return 'failed';
        }
    });
}
$(document).ready(function(){
   $('.btn').click(function(){
       var apiData = getData();
       console.log(apiData);
   });
});

因此,如果 api 返回不为 0 的错误代码,则函数 getData 应返回“失败”字符串,但它返回数据元素。我知道代码不是 0,因为 console.log 显示代码是 999。我做错了什么?为什么我不能让它返回“失败”字符串?

最佳答案

getData 不(也不能)返回数据或“失败”;它返回一个 promise 。您使用该 promise 的方式与在 getData 中所做的方式非常相似:

$(document).ready(function(){
   $('.btn').click(function(){
       getData().done(function(apiData) {   // **
           console.log(apiData);            // **
       });                                  // **
   });
});

在该回调中,apiData 将是您在 getData 中返回的回调,因此它将是数据对象或字符串“failed”.

(我在那里使用了 done ,因为它是您在其他地方使用的,但通常我会使用 then,标准的 Promise 函数。)

关于 Promise 需要理解的关键事情之一是 then (和 done)返回一个新的 Promise (从技术上讲,具有真正的 Promise ,一个thenable),将根据回调的作用进行结算。

所以考虑一下(现在让我们继续使用 jQuery 的 Deferred):

function doSomething() {
  var d = $.Deferred();
  setTimeout(function() {
    // Resolve our promise with "a"
    d.resolve("a");
  }, 10);
  return d.promise();
}

// Consume the promise and put it through a chain:
doSomething()
  .then(function(result) {
    // This callback happens to do synchronous processing
    console.log("First callback got", result);
    return result.toUpperCase();
  })
  .then(function(result) {
    // This one does something async, and so it returns a promise
    var cd = $.Deferred();
    setTimeout(function() {
      console.log("Second callback got", result);
      cd.resolve(result + result);
    }, 10);
    return cd.promise();
  })
  .then(function(result) {
    console.log("Third callback got", result);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

其输出是

First callback got a
Second callback got A
Third callback got AA

Now, earlier I said then always returns a promise (thenable). How does it do that when my first callback is synchronous and returns a value directly, but my second one is async and returns a promise? The then function looks at the return value from the callback and, if it's "thenable" (something with then on it), returns it; if it's not thenable, it creates a new, resolved promise with the value as the resolution value.


Just for completeness, here's the example above with native JavaScript promises (requires browser support):

function doSomething() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      // Resolve our promise with "a"
      resolve("a");
    }, 10);
  });
}

// Consume the promise and put it through a chain:
doSomething()
  .then(function(result) {
    // This callback happens to do synchronous processing
    console.log("First callback got", result);
    return result.toUpperCase();
  })
  .then(function(result) {
    // This one does something async, and so it returns a promise
    return new Promise(function(resolve) {
      setTimeout(function() {
        console.log("Second callback got", result);
        resolve(result + result);
      }, 10);
    });
  })
  .then(function(result) {
    console.log("Third callback got", result);
  });

其输出是

First callback got a
Second callback got A
Third callback got AA

关于javascript - jQuery .done 未按预期返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37927566/

相关文章:

jquery - Request.IsAjaxRequest() 在 MVC4 中总是返回 false,尝试了 SO 中的所有建议等

javascript - 是否可以本地扩展 Web API 以允许 CSSRule.cssText 返回非标准 css 属性

当我更改选择框时,jQuery 删除 div

android - Phonegap/ Cordova : get images from server

javascript - jQuery:从上到下切换 ('slow' ) 动画?

java - Jquery函数将java数据转换为json

php - 使用ajax调用PHP函数不起作用

javascript - Lodash:_.has 检查返回 false 的键

Javascript 搜索确切结果不属于

php - 如何创建 "you are here"导航