Search code examples
javascriptasync-awaites6-promise

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:

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