是否等待删除“然后”?
为什么在以下情况下使用then会导致此错误:
// Error: [dart] The method 'then' isn't defined for the class 'String'. [undefined_method]
here的修改后的代码
import 'dart:async';
Future<void> printDailyNewsDigest() async {
var newsDigest = await gatherNewsReports();
// Error: [dart] The method 'then' isn't defined for the class 'String'. [undefined_method]
newsDigest.then(print);
// print(newsDigest);
}
main() {
printDailyNewsDigest();
printWinningLotteryNumbers();
printWeatherForecast();
printBaseballScore();
}
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);
// Imagine that this function is more complex and slow. :)
Future<String> gatherNewsReports() =>
Future.delayed(oneSecond, () => news);
最佳答案
await
不会“删除” then
,但它允许像then
一样以更方便的语法编写异步代码,并且可以替换then
。
然后,编译器将await
重新写回then
。await
延迟以下代码的执行,直到完成等待的异步操作的结果并返回结果值。
结果值不再是Future
,因此then()
不可用。
关于dart - 那么Dart等待移除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498805/