Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch api doesn't return data but a Promise

I am calling fakestoreapi with fetch by creating an async function. I am returning await response.json(); but at the end I am getting a Promise. Even if I try to declare a variable outside this function and assign data = await response.json(); it is undefined. But when I console.log(data) then it logs the actuall data to console. My code is:

//let products = [];

const getProducts = async () => {
 const response = await fetch('https://fakestoreapi.com/products');
 const data = await response.json();
 console.log(data);// this works and logs data to console
 //products = data; this is undefined when logged to console.
 return data; // this gives back a promise.
}

console.log(getProducts());
console.log(products);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

According to docs:

Each time when an async function is called, it returns a new Promise which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.

So, the async function always return a promise.

You need to resolve it first:

//let products = [];

const getProducts = async () => {
   const response = await fetch('https://fakestoreapi.com/products');
   const data = await response.json();
   console.log(data);// this works and logs data to console
   //products = data; this is undefined when logged to console.
   return data; // this gives back a promise.
}

getProducts().then(products => {
    console.log(products);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading