簡體   English   中英

異步/等待 - Python 與 Javascript?

[英]Async/Await - Python vs Javascript?

我試圖理解異步編程,即 async/await。 我目前的理解是,使用 await 關鍵字將等待 promise 在繼續之前解決。 考慮到這一點,我在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()

寫劇本的時候,我以為他們會做同樣的事情。 但是,output 不同。

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 }

這是 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

它不應該總共需要8秒嗎? 我說 Javascript 將等待 hello() 而不是 main 方法中的 stall() 是否正確? 如果是這樣,為什么 Javascript 不等待 stall() 完成? 如果不是,等待這兩個函數時 Javascript 在做什么?

抱歉,如果答案很明顯或者我犯了一些愚蠢的錯誤。

您從stall返回的 promise 永遠不會穩定(它永遠不會被滿足或拒絕),最終會在第一次await時無限期地暫停您的hello() function。 要實現您使用new Promise()創建的 promise,您需要在其執行程序 function 中調用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM