简体   繁体   中英

Async/Await - Python vs Javascript?

I am trying to understand asynchronous programming, namely async/await. My current understanding is that using the await keyword will wait for a promise to resolve before continuing on. With this in mind, I made two scripts in Python and 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()

When writing the scripts, I thought they would do the same thing. However, the output is different.

Python:

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

Javascript:

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

Using Powershell, I typed this command:

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

and this is the output:

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

Shouldn't it take a total of 8 second? Am I correct in saying that Javascript will wait for hello() but not stall() in the main method? If so, why doesn't Javascript wait for stall() to finish? If not, what is Javascript doing when awaiting the two functions?

Sorry if the answer is obvious or if I made some silly mistake.

The promise you're returning from stall never settles (it is never fulfilled or rejected) which ends up suspending your hello() function indefinitely at its first await . To fulfil a promise that you create using new Promise() , you need to call resolve() within its executor function. You can do this by updating the executor to use the resolveFunc it gets passed and then call that when the setTimeout() callback is called:

 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM