Fetch api doesn't return data but a Promise

Advertisements

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 :

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);
});

Leave a ReplyCancel reply