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.
Any idea please, how to turn it into an Object saved in the 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.
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.
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.
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); }
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
More details: https://medium.com/@pprathameshmore/top-level-await-support-in-node-js-v14-3-0-8af4f4a4d478
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With