当等待挂起异步功能时会发生什么?

时间:2019-06-21 09:03:19

标签: javascript async-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()挂起,将控制权传递回GoShopping()

然后运行printWinningLotteryNumbers,printWeatherForecast和printBaseballScore。如果等待仍未返回,接下来会发生什么?

它返回上一级然后运行HaveAGoodDay()For Each ws In ThisWorkbook.Worksheets If ws.Name<>"Post" Then ws.Protect Password:=UniquePassword ws.Visible = False End If Next 吗?

1 个答案:

答案 0 :(得分:1)

  

第一个PrintLotsOfStuff()调用printDailyNewsDigest(),后者调用collectNewsReports,然后将其挂起,将控制权传递回printLotsOfStuff()。

完全正确。换句话说:printDailyNewsDigest()同步执行,直到到达第一个await,然后函数产生其执行,并且函数调用求值为Promise(因此Promise将返回给调用它的函数)。由于PrintLotsOfStuff()忽略了这个承诺,因此执行将从那时起继续同步。

  

然后运行printWinningLotteryNumbers,printWeatherForecast和printBaseballScore。如果等待仍未返回,接下来会发生什么?

不能中断同步执行。 printDailyDiggest显然还没有继续执行。

  

它返回上一级,然后运行GoShopping()和HaveAGoodDay()吗?

好的。

现在,如果已完成,则调用堆栈为空,并且引擎有时间执行下一个任务。现在,等待printDailyDiggest的任何事情都会完成,而printDailyDiggest将会继续执行