Javascript Fetch API - 如何将输出作为对象保存到变量(而不是 Promise)

新手上路,请多包涵

请问,如何将 fetch 的输出保存到变量中——以便能够像处理对象一样使用它?

这是代码:

 var obj;
fetch("url", {
  method: "POST",
  body: JSON.stringify({
    "filterParameters": {
      "id": 12345678
    }
  }),
  headers: {"content-type": "application/json"},
  //credentials: 'include'
})
.then(res => res.json())
.then(console.log)

最后的 console.log 将显示一个对象。但是当我试图将它保存到变量 .then(res => obj = res.json()) 而不是 console.log(obj) 将不会保存对象,而是 Promise。

安慰

请问,如何将它变成保存在变量中的对象?

原文由 Vlasta Po 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

.json() 是一个async方法(它返回一个Promise本身),所以你必须在接下来分配解析值 .then()

 var obj;

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(res => res.json())
  .then(data => {
    obj = data;
   })
  .then(() => {
    console.log(obj);
   });

现代异步/等待等效

你必须 await .json() 方法。

 async function foo() {
  let obj;

  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')

  obj = await res.json();

  console.log(obj)
}

foo();

原文由 yuriy636 发布,翻译遵循 CC BY-SA 4.0 许可协议

与其存储在变量中,不如创建一个返回数据的函数,然后将其存储在变量中。所以它可以在你的整个文件中访问。

 async function fetchExam(id) {
        try {
            const response = await fetch(`/api/exams/${id}`, {
                method: 'GET',
                credentials: 'same-origin'
            });
            const exam = await response.json();
            return exam;
        } catch (error) {
            console.error(error);
        }
    }

然后调用该函数获取数据

async function renderExam(id) {
        const exam = await fetchExam(id);
        console.log(exam);
}

更新

使用当前版本的 Node.js v14.3.0 支持顶级异步等待

import axios from 'axios';

const response = await axios('https://quote-garden.herokuapp.com/api/v3/quotes/random');
console.log(response.data);

使用运行此文件 node --harmony-top-level-await top-level-async-await.js

输出

输出

更多详情: https ://medium.com/@pprathameshmore/top-level-await-support-in-node-js-v14-3-0-8af4f4a4d478

原文由 Prathamesh More 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题