javascript - 为什么 .json() 返回一个 promise ?

标签 javascript asynchronous promise fetch-api

我最近一直在弄乱 fetch() api,并注意到一些有点古怪的东西。

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => {
      return {
          data: response.json(),
          status: response.status
      }
  })
  .then(post => document.write(post.data));
;

post.data 返回一个 Promise 对象。 http://jsbin.com/wofulo/2/edit?js,output

但是如果写成:

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => response.json())
  .then(post => document.write(post.title));
;

post 这里是一个标准的 Object,您可以访问它的 title 属性。 http://jsbin.com/wofulo/edit?js,output

所以我的问题是:为什么 response.json 在对象字面量中返回一个 promise,但如果刚返回就返回值?

最佳答案

Why does response.json return a promise?

因为您会在所有 header 到达后立即收到响应。调用 .json() 为尚未加载的 http 响应正文提供另一个 promise 。另见 Why is the response object from JavaScript fetch API a promise? .

Why do I get the value if I return the promise from the then handler?

因为 that's how promises work .从回调中返回 promise 并让它们被采用的能力是它们最相关的特性,它使它们无需嵌套即可链接。

你可以使用

fetch(url).then(response => 
    response.json().then(data => ({
        data: data,
        status: response.status
    })
).then(res => {
    console.log(res.status, res.data.title)
}));

或任何其他 approaches to access previous promise results in a .then() chain在等待 json 正文后获取响应状态。

关于javascript - 为什么 .json() 返回一个 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37555031/

相关文章:

javascript - Three.js 截图

javascript - 'this' 没有选择 jquery 函数

c# - 在 C# 中将 Task<T> 转换为 Task<object> 而无需 T

c# - async/await 是否可以感知 Android Activity 生命周期?

javascript - 拒绝并终止对外部事件的 promise

Javascript Promises - 在 for 循环之前保存项目

javascript - 使文本在类型上淡出

javascript - Ember 框架中使用的 promise 实现

javascript - 在 JavaScript 函数中执行 Firestore 查询

javascript - 根据组合框值的变化改变两个文本框的值