并行多个等待
我正在尝试学习异步/等待和承诺,并且无法在串行中运行多个异步功能。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要移动 resolve()在 settimeout()函数中呼叫。这是固定的代码:
You need to move your resolve() call inside setTimeout() function. Here is the fixed code: