Javascript Fetch API - How to save output to variable as an Object (not the Promise)
For a modern async/await approach refer to @PrathameshMore's answer below
.json()
is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then()
var obj;
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => obj = data)
.then(() => console.log(obj))
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);
}
Update
With the current version of Node.js v14.3.0 support 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);
Running this file using node --harmony-top-level-await top-level-async-await.js
Output
More details: https://medium.com/@pprathameshmore/top-level-await-support-in-node-js-v14-3-0-8af4f4a4d478