为什么要达到此输出?

发布于 2025-01-19 08:50:28 字数 811 浏览 1 评论 0原文

谁能告诉我为什么这段代码会输出以下内容?我完全迷失在异步函数上,几乎要放弃了。

第一个等待按照我的预期执行,并在执行前等待 1 秒。然而,不知怎的,301 是在执行之前在 then 之前输出的,这似乎完全违背了 then 的字面定义。 Done 被输出,然后以某种方式返回并执行第二个 then 语句。

async function test() {

  const promise1 = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('foo');
      console.log('First await executed')
    }, 1000)
  }).then(() => {
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('foo');
        console.log("This was executed")
      }, 1000)
    })
  }).then(() => Promise.resolve(301));

  console.log(promise1)

  await setTimeout(() => console.log(1000), 1000)

  console.log("Done");
}

test()

Can anyone tell me why this code outputs the following? I am completely lost on async functions and close to just giving up.

The first await does what I expect and waits 1 second before executing. However, somehow 301 is outputted before the then before it is executed which seems to completely defy the literal definition of then. Done is outputted then somehow it goes back and executes the second then statement.

async function test() {

  const promise1 = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('foo');
      console.log('First await executed')
    }, 1000)
  }).then(() => {
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('foo');
        console.log("This was executed")
      }, 1000)
    })
  }).then(() => Promise.resolve(301));

  console.log(promise1)

  await setTimeout(() => console.log(1000), 1000)

  console.log("Done");
}

test()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文