异步IIFE后变量未定义
let groupedWishlistProducts;
(async function () {
groupedWishlistProducts = await fetchGroupedWishlistProducts();
console.log(groupedWishlistProducts); // logs returned value properly
})();
console.log(groupedWishlistProducts); // logs undefined
为什么groupedWishlistProducts在全局范围内未定义,即使我已经在全局范围内初始化?
回答
它是未定义的,因为您还没有为其分配任何东西(还)。
事情被执行的顺序是:
- 声明变量
- 声明并开始执行 IIFE
- 调用 fetchGroupWishlistProducts
- 到达 后
await,IIFE 现在返回到外部代码。 - 记录 groupedWishlistProducts(函数外)
- 一段时间后,来自 fetchGroupedWishlistProducts 的承诺得到解决,异步函数恢复
- 将 fetchGroupedWishlistProduct 的 promise 的结果分配给 groupedWishlistProducts
- 记录 groupedWishlistsProducts(函数内部)
- #4 Should read *"Due to the async, the IIFE now returns a promise"*