请问,如何将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)
将不会保存对象,而是承诺。
请问,如何把它变成保存在变量中的对象?
答案 0 :(得分:11)
创建一个将返回数据的函数而不是存储在变量中,然后将其存储在变量中。因此它可以在您的整个文件中访问。
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中,支持顶级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
答案 1 :(得分:9)
.json()
是一个异步方法(它本身返回一个Promise),所以你必须在下一个.then()
var obj;
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => obj = data)
.then(() => console.log(obj))
答案 2 :(得分:3)
你可以这样做。首先获取数据并创建一个函数来处理数据。
然后将结果传递给该函数并在任何地方访问它。
fetch('https://pokeapi.co/api/v2/pokemon/ditto')
.then(jsonData => jsonData.json())
.then(data => printIt(data))
let printIt = (data) => {
console.info(typeof data)
}
答案 3 :(得分:1)
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 :(得分:0)
最简单的方法是使用 async/await 方法。
只需将以下代码复制并粘贴到您的 chrome 开发控制台中即可查看效果:
async function githubUsers() {
let response = await fetch('https://api.github.com/users')
let users = await response.json()
console.log(users)
}
githubUsers()