并行多个等待

发布于 2025-02-11 06:02:05 字数 624 浏览 0 评论 0原文

我正在尝试学习异步/等待和承诺,并且无法在串行中运行多个异步功能。

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('first'), 2000)
    resolve()
  })
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('second'), 1000)
    resolve()
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

我要获得的输出是

second
first

因为正在等待firstFunction(),所以我希望第一函数()的承诺能够在转到secondfunction()之前完成。

有人可以指出为什么他们并行跑步,以及如何使他们彼此奔跑? (在节点V18.3.0中运行)

I'm trying to learn async/await and promises and unable to make run multiple async functions in serial.

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('first'), 2000)
    resolve()
  })
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('second'), 1000)
    resolve()
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

Output I am getting is

second
first

Since there's an await for firstFunction(), I'd expect the promise of firstFunction() to finish before going to secondFunction().

Can someone point out why they ran in parallel and how to make them run one after the other? (ran in node v18.3.0)

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

卷耳 2025-02-18 06:02:05

您需要移动 resolve() settimeout()函数中呼叫。这是固定的代码:

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('first');
      resolve();
    }, 2000);
  });
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('second');
      resolve();
    }, 1000);
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

You need to move your resolve() call inside setTimeout() function. Here is the fixed code:

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('first');
      resolve();
    }, 2000);
  });
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('second');
      resolve();
    }, 1000);
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文