javascript - 当 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()
?
解决方案
首先 PrintLotsOfStuff() 调用 printDailyNewsDigest(),后者调用gatherNewsReports,然后暂停,将控制权传回给 printLotsOfStuff()。
确切地。换句话说:printDailyNewsDigest()
同步执行直到它到达 first await
,然后函数产生它的执行并且函数调用评估为 Promise (因此 Promise 被返回给调用它的函数)。由于PrintLotsOfStuff()
忽略了该承诺,从那时起执行将继续同步。
然后运行 printWinningLotteryNumbers、printWeatherForecast 和 printBaseballScore。如果 await 仍然没有返回,接下来会发生什么?
同步执行不能被中断。printDailyDiggest
肯定还没有继续执行。
它是否返回上层然后运行 GoShopping() 和 HaveAGoodDay()?
当然。
现在如果这样做了,调用堆栈是空的,引擎有时间执行下一个任务。现在某个时候,无论printDailyDiggest
等待什么都将完成,printDailyDiggest
并将继续执行
推荐阅读
- ios - 一般问题,有什么建议吗?
- html - 使滚动成为元素的最佳方法
- twitter-bootstrap - Bootstrap 3 当列高增加时推动整行
- c++ - 任务:需要 OpenMP 指令名称
- angular - 如何仅将插入符号添加到Angular 4中的选定列
- android - 使用我的android应用程序在magento 2中完成的rest api将数据发布到mysql数据库?
- python - 如何在 Python 中使用 XPath 选择兄弟节点的子节点?
- c# - RavenDB:在 Raven 4.0 中将自动增量添加到除 ID 之外的其他属性
- count - defaultdict的自动更改(python 3)
- sql - SQL 加入最新记录