Skip to content
Advertisement

console logging prints a promise when function returns an object but prints the data when it is not an object

I have this function that makes a get request to an api

JavaScript

When I use this function on a buttons onClick handler

JavaScript

The console shows an a promise not the actual data

but when I switch my get function to

JavaScript

where it isn’t returning an object around the data, then access the data by

JavaScript

the console prints out the actual data. Why does this happen? I would much prefer to do it the first way and add an extract key for error but this logging issue is really annoying me

Advertisement

Answer

In the first way:

JavaScript

keep in mind that response.json() itself returns a promise.

So you’re saying return {data: <Promise>}.

The reason that the second one works is because you’re returning the promise directly in an async function,

JavaScript

When you return a promise from an Async function, get().then(... resolves the promise like normal, so you’re getting the proper data you expect out.

If you want to do the first way, await it first:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement