Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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.log will 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

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

like image 909
Vlasta Po Avatar asked Jul 10 '17 17:07

Vlasta Po


People also ask

How do you store results of fetch response in JavaScript variable?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

How do I get a response object from Fetch?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

Does fetch API return a promise?

fetch() starts a request and returns a promise. When the request completes, the promise is resolved with the Response object. If the request fails due to some network problems, the promise is rejected.


Video Answer


2 Answers

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))
like image 185
yuriy636 Avatar answered Sep 18 '22 14:09

yuriy636


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/v3/quotes/random'); console.log(response.data); 

Running this file using node --harmony-top-level-await top-level-async-await.js

Output

output

More details: https://medium.com/@pprathameshmore/top-level-await-support-in-node-js-v14-3-0-8af4f4a4d478

like image 22
Prathamesh More Avatar answered Sep 18 '22 14:09

Prathamesh More