这页给的示例代码,我始终打印不出来gathered news goes here,后来看到说是async方法要在第一次遇到await或者return的时候才会执行里面的代码,于是我就在把main函数标记为async,然后await printDailyNewsDigest(),这样才打印出来。
可是这样感觉不是变同步的了么?
顺便问下,有没有Dart交流学习群啊
你的感觉没有错啊,async/await 就是将乱序的异步代码重新变得有序,就是使用同步方式书写异步代码。很多语言如 Nodejs、C#、Python等都有async/await的,它们只是编译器提供的语法糖,代码在编译时会被转换成callback/promise/generator等方式。
main() {
//我是这么写的await printDailyNewsDigest();官网上是下面这么写的
printDailyNewsDigest();
printWinningLotteryNumbers();
printWeatherForecast();
printBaseballScore();
}
Future<void> printDailyNewsDigest() async {
var newsDigest = await gatherNewsReports();
print(newsDigest);
}
printWinningLotteryNumbers() {
print('Winning lotto numbers: [23, 63, 87, 26, 2]');
}
printWeatherForecast() {
print("Tomorrow's forecast: 70F, sunny.");
}
printBaseballScore() {
print('Baseball score: Red Sox 10, Yankees 0');
}
const news = '<gathered news goes here>';
const oneSecond = Duration(seconds: 1);
Future<String> gatherNewsReports() =>
Future.delayed(oneSecond, () => news);
但是按照他文档里的: Notice that printDailyNewsDigest()
is the first function called, but the news is the last thing to print
现在是2个问题
1、按照上面这么写,打印不出第7步
2、如果换成await printDailyNewsDigest();的话,感觉跟官网表达的意思不一样
官网感觉就像是开了个子线程的效果,而await printDailyNewsDigest()只有等它执行完了才执行下面的代码,不明白哪里有问题
我把文件从test目录下移到lib目录下,运行app就正常了。。。直接右键运行单个dart文件为啥不行。。。。
难道学习的时候每次都要运行整个app么?
嗯嗯,好的。十分感谢~