Search code examples
javascriptasync-awaitiife

Variable is undefined after async IIFE


  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?


Solution

  • 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)