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

问题描述 投票:0回答:7

请问,如何将 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。

Console

请问有什么想法,如何将其转换为保存在变量中的对象吗?

javascript fetch-api
7个回答
88
投票

.json()
是一个异步方法(它本身返回一个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();


30
投票

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

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

运行此文件

输出

{
    statusCode: 200,
    quote: {
        _id: '5db17aaeb69dc744b4e72b82',
        quoteText: 'I can take more punishment than anyone in the business.',
        quoteAuthor: 'Ric Flair',
        quoteGenre: 'business',
        __v: 0
    }
}

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


11
投票

你可以这样做。首先获取数据并创建一个函数来对数据执行某些操作。

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

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

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

4
投票

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)
  


4
投票

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

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));

0
投票

我以前做过这个。其实很简单。以下是我使用有时使用的 API 实现的方法:

x = await fetch("https://api.quotable.io/random").then((res)=>res.json()).then((json)=>json.content)
console.log(x) // Returns 'The world cares very little about what a man or woman knows; it is what a man or woman is able to do that counts.'

或者,您也可以这样做:

x = fetch("https://api.quotable.io/random").then((res)=>res.json()).then((json)=>json.content)
console.log(await x) // Returns 'The world cares very little about what a man or woman knows; it is what a man or woman is able to do that counts.'

-1
投票

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

只需将以下代码复制并粘贴到您的 Chrome 开发控制台中即可看到魔法:

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

githubUsers()
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.