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

Promise not resolving even with status of fulfilled and target data on PromiseResult

I need help on this issue I’m experiencing (I have already searched Stack overflow extensively but could not solve it on my own).

I have the following "dummy" logic to test async/await behaviour:

const data = [1, 2, 3]

async function newData() {
  return data
}

async function getData() {
  const fetchedData = await newData();
  return fetchedData
}

console.log(
  (async () => await getData())()
)

Even though I have awaited for all Promise fulfillings, the following data is returned from the console log:

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

Console.log return

What am I doing wrong? Why doesn’t the Promise return the value but remains pending even though it is ‘fulfilled’?

Thanks in advance.

>Solution :

All async functions return a promise. That’s why newData(), getData() and your async IIFE you have buried in a console.log() ALL return a promise. When you return a value from an async function, that returned value just become the resolved value of the promise that the async function returns. An async function NEVER returns the value directly.

So, even this:

(async () => await getData())()

is an async function that returns a promise.

To get the resolved value from an async function, you MUST use .then() or await:

// this must be inside an async function or
// in an environment where top level await is allowed
console.log(await getData());

or:

getData().then(result => {
    console.log(result);
});
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