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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45018338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:52:02  来源:igfitidea点击:

Javascript Fetch API - How to save output to variable as an Object (not the Promise)

javascriptfetch-api

提问by Vlasta Po

Please, how can I save output of fetch to a variable - to be able to work with it as with an object?

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

Here is the code:

这是代码:

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)

The final console.logwill show an object. But when I tried to save it to variable .then(res => obj = res.json())than the console.log(obj)will not hold the Object, but the Promise.

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

Console

安慰

Any idea please, how to turn it into an Object saved in the variable?

任何想法,如何将其转换为保存在变量中的对象?

回答by yuriy636

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

对于现代异步/等待方法,请参阅下面的@PrathameshMore 的回答



.json()is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then()

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

var obj;

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

回答by Prathamesh More

Instead of storing in a variable, create a function that will return data, and then store it in a variable. So It can accessible in your whole file.

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

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

Then call that function to get data

然后调用该函数获取数据

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