首页 > 解决方案 > 为什么我的嵌套等待函数没有等待

问题描述

我不明白为什么下面的函数运行得这么快,底层异步函数在 0.06 秒内运行,而不是我预期的 2.06 秒(在 sleep 函数之后)。

const hiWorld = () => {
   const final = await Promise.all(
    firstLevelArray.map(async (secondLevelArray) => {
      const topLevelResponse = await Promise.all(
        secondLevelArray.map(async (item) => {         
          const asyncResponse = await myAsyncFunction({
            item: item,
          });
          console.log(new Date()) // this shows that it's running within .06 seconds instead of 2.06 seconds
          await new Promise(r => setTimeout(r, 2000)); 
          return asyncResponse
        })
      );
      return topLevelResponse
    })
  );
  return final 
}

如果它很重要,这与 Typescript 一起使用。

这是console.log:

2021-04-07T01:45:02.501Z

2021-04-07T01:45:02.552Z

2021-04-07T01:45:02.619Z

标签: javascripttypescriptasync-await

解决方案


推荐阅读