1
  let groupedWishlistProducts;

  (async function () {
      groupedWishlistProducts = await fetchGroupedWishlistProducts();
      console.log(groupedWishlistProducts); // logs returned value properly
  })();

  console.log(groupedWishlistProducts); // logs undefined

Why is groupedWishlistProducts undefined on global, even if I have initialized in global scope?

Badal Saibo
  • 2,499
  • 11
  • 23
  • Does this answer your question? [Why async/await variable return undefined?](https://stackoverflow.com/questions/46715291/why-async-await-variable-return-undefined) – Mister Jojo Dec 19 '20 at 05:17
  • Sorry, no. I'd like to know the order of execution for each steps. – Badal Saibo Dec 19 '20 at 06:17

2 Answers2

5

It's undefined because you havn't assigned anything to it (yet).

The order that things get executed is:

  1. Declare the variable
  2. Declare and begin executing the IIFE
  3. Call fetchGroupWishlistProducts
  4. Having reached an await, the IIFE now returns to the outer code.
  5. Log groupedWishlistProducts (outside the function)
  6. Some time later, the promise from fetchGroupedWishlistProducts resolves, and the async function resumes
  7. Assign the result of fetchGroupedWishlistProduct's promise to groupedWishlistProducts
  8. Log groupedWishlistsProducts (inside the function)
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • 2
    #4 Should read *"Due to the async, the IIFE now returns a promise"* – charlietfl Dec 19 '20 at 05:20
  • I'm describing the order things happen, so #4 is describing *when* it returns. The `await` keyword is what causes it to return at that time, as opposed to another time. I've reworded it to emphasis the time, not the value. – Nicholas Tower Dec 19 '20 at 05:21
2

async function returns Promise, so by the time you execute IIFE, the Promise is still pending, as the result fetchGroupedWishlistProducts() would not be resolved. So in your case, second console.log will be executed first, and is undefined

To handle this, you could wrap it into another IIFE

let groupedWishlistProducts;

(async function() {
  
  await (async function () {
    groupedWishlistProducts = await fetchGroupedWishlistProducts();
    console.log(groupedWishlistProducts); // logs returned value properly
  })();

  console.log(groupedWishlistProducts);

})()

or just resolve the promise

let groupedWishlistProducts;

(async function () {
  groupedWishlistProducts = await fetchGroupedWishlistProducts();
  console.log(groupedWishlistProducts); // logs returned value properly
})().then(() => {
  console.log(groupedWishlistProducts);
})
hgb123
  • 13,869
  • 3
  • 20
  • 38