Async/Await - Python vs Javascript?



我正在尝试理解异步编程,即async/await。我目前的理解是,使用await关键字将等待一个承诺解决之前继续。考虑到这一点,我用Python和Javascript编写了两个脚本。

Python:

import asyncio

async def stall(func, s):
await asyncio.sleep(s)
func()
async def hello():
def stop():
print("hello() stop")
print("hello() start")
await stall(stop, 5)
async def main():
def stop():
print("main() stop")
print("main() start")
await asyncio.create_task(hello())
await asyncio.create_task(stall(stop, 3))
asyncio.run(main())

Javascript:

function stall(func, ms) {
return new Promise(() => {
setTimeout(func, ms)
})
}
async function hello() {
console.log("hello() start")
await stall(() => {console.log("hello() stop")}, 5000)
}
async function main() {
console.log("main() start")
await hello()
await stall(() => {console.log("main() stop")}, 3000)
}
main()

在编写脚本时,我认为他们会做同样的事情。但是,输出是不同的。

Python:

main() start
hello() start
hello() stop
main() stop

Javascript:

main() start
hello() start
hello() stop

使用Powershell,我输入了这个命令:

Measure-Command { node .async_await.js | out-default }

,这是输出:

main() start
hello() start
hello() stop

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 5
Milliseconds      : 121
Ticks             : 51210409
TotalDays         : 5.9271306712963E-05
TotalHours        : 0.00142251136111111
TotalMinutes      : 0.0853506816666667
TotalSeconds      : 5.1210409
TotalMilliseconds : 5121.0409

不应该总共花8秒吗?我是否正确地说,Javascript将等待hello(),而不是stall()在主方法?如果是这样,为什么Javascript不等待stall()完成呢?如果不是,Javascript在等待这两个函数时在做什么?

如果答案很明显或者我犯了一些愚蠢的错误,我很抱歉。

您从stall返回的承诺永远不会解决(它永远不会完成或拒绝),最终在其第一个await无限期地暂停您的hello()功能。要实现使用new Promise()创建的承诺,需要在其执行器函数中调用resolve()。您可以通过更新执行器来使用它传递的resolveFunc,然后在调用setTimeout()回调时调用它:

function stall(func, ms) {
return new Promise((resolve) => { // use the resolveFunc
setTimeout(() => {
resolve(); // resolve the promise
func();
}, ms);
});
}
async function hello() {
console.log("hello() start");
await stall(() => {console.log("hello() stop")}, 5000);
}
async function main() {
console.log("main() start");
await hello();
await stall(() => {console.log("main() stop")}, 3000);
}
main();

最新更新