【问题标题】:Javascript Fetch API - How to save output to variable as an Object (not the Promise)Javascript Fetch API - 如何将输出作为对象保存到变量(不是承诺)
【发布时间】:2017-12-14 13:25:32
【问题描述】:

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

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

【问题讨论】:

    标签: javascript fetch-api


    【解决方案1】:

    For a modern async/await approach refer to @PrathameshMore's answer below


    .json() 是一个异步方法(它本身返回一个 Promise),因此您必须在下一个 .then() 中分配解析后的值

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

    【讨论】:

    • 非常感谢,.then(data => obj = data) 是缺失的部分,现在可以正常工作了。
    • 嘿,Yuri,如果第三个 then 不是匿名函数,你能解释一下为什么这段代码会中断吗?
    • @Vayl 你能在 jsfiddle 中创建一个复制品吗?我刚刚尝试将代码提取到一个函数中,它仍然可以按预期工作。
    • 感谢您回复@yuriy636,因为我在写小提琴时我想通了(当然)。不过,感谢后续行动,干杯?。
    【解决方案2】:

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

    async 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 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/v2/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

    【讨论】:

    • 如何在整个文件中访问这个变量“exam”?似乎你被困在函数 renderExam 中(当我尝试“返回”时,它就像原来的问题一样悬而未决。请赐教:-)。
    • 我犯了一个错误。它只能访问功能。我们可以在函数之外定义一个 var 检查。请原谅我的错误。
    【解决方案3】:

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

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

    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)
        

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

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

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

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

          【讨论】:

            猜你喜欢
            • 2020-08-15
            • 2020-10-14
            • 2023-04-07
            • 2021-03-10
            • 2019-08-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多