首页 > 解决方案 > 当 await 挂起一个异步函数时会发生什么?

问题描述

main(){
    PrintLotsOfStuff();
    GoShopping();
    HaveAGoodDay();

}

PrintLotsOfStuff(){
    printDailyNewsDigest();
    printWinningLotteryNumbers();
    printWeatherForecast();
    printBaseballScore();
}

async printDailyNewsDigest() {
   var newsDigest = await gatherNewsReports();
   print (newsDigest);
}

gathernewsReports() {}

如果我们查看https://dart.dev/tutorials/language/futures,我们可以看到 collectNewsReport() 和 print(newsDigest) 在调用异步函数的函数中的所有函数之后运行。

但是,在我上面概述的情况下,还有一个级别。在这种情况下,流程看起来如何?

首先PrintLotsOfStuff()调用printDailyNewsDigest(),然后调用gatherNewsReports(),然后挂起,将控制权交还给printLotsOfStuff()

然后运行 ​​printWinningLotteryNumbers、printWeatherForecast 和 printBaseballScore。如果 await 仍然没有返回,接下来会发生什么?

它是否返回上层然后GoShopping()运行HaveAGoodDay()

标签: javascriptasync-await

解决方案


首先 PrintLotsOfStuff() 调用 printDailyNewsDigest(),后者调用gatherNewsReports,然后暂停,将控制权传回给 printLotsOfStuff()。

确切地。换句话说:printDailyNewsDigest()同步执行直到它到达 first await,然后函数产生它的执行并且函数调用评估为 Promise (因此 Promise 被返回给调用它的函数)。由于PrintLotsOfStuff()忽略了该承诺,从那时起执行将继续同步。

然后运行 ​​printWinningLotteryNumbers、printWeatherForecast 和 printBaseballScore。如果 await 仍然没有返回,接下来会发生什么?

同步执行不能被中断。printDailyDiggest肯定还没有继续执行。

它是否返回上层然后运行 ​​GoShopping() 和 HaveAGoodDay()?

当然。

现在如果这样做了,调用堆栈是空的,引擎有时间执行下一个任务。现在某个时候,无论printDailyDiggest等待什么都将完成,printDailyDiggest并将继续执行


推荐阅读