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

Javascript Fetch API - How to save output to variable as an Object (not the 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。

请问如何把它变成一个保存在变量中的对象?


.json() 是一个异步方法(它 returns 本身就是一个 Promise),所以你必须在接下来的 .then()

中分配解析的值

var obj;

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

创建一个将 return 数据存储在变量中的函数,而不是存储在变量中。所以它可以在你的整个文件中访问。

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 支持Top-Level async-await

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

最简单的方法是使用 async/await 方法。

只需将以下代码复制并粘贴到您的 chrome 开发控制台即可看到神奇之处:

async function githubUsers() {
            let response = await fetch('https://api.github.com/users')
            let users = await response.json()
            console.log(users)
    }

githubUsers()

你可以这样做。首先获取数据并创建一个函数来处理数据。

然后将结果传递给该函数并在任何地方访问它。

fetch('https://pokeapi.co/api/v2/pokemon/ditto')
    .then(jsonData => jsonData.json())
    .then(data => printIt(data))

let printIt = (data) => {
    console.info(typeof data)
}

let data = [];

async function getRandomUser(){
  // gets the response from the api and put it inside a constant
  const response = await fetch('https://randomuser.me/api');
  //the response have to be converted to json type file, so it can be used
  const data = await response.json();
  //the addData adds the object "data" to an array
  addData(data)
}

function addData(object) {
  // the push method add a new item to an array
  // here it will be adding the object from the function getRandomUser each time it is called
  data.push(object);
  //the fetched data is available only on this scope
  console.log("This is the value of date inside the function addData:")
  console.log(data)
}

//Calls the function that fetches the data
getRandomUser()

  console.log("This is the value of data outside the scope")
  console.log(data)
  

一个简单方便的解决方案是:

function myFunc(success) {
//do what you want HERE.

console.log(success)

}

fetch('https://reqres.in/api/users?page=2')
    .then(data => data.json())
    .then(success => myFunc(success));