首页 > 解决方案 > Dart 等待删除呢?

问题描述

等待删除“然后”吗?

为什么在下面使用 then 时会导致此错误:

// Error: [dart] The method 'then' isn't defined for the class 'String'. [undefined_method]

从这里修改代码

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);    

标签: dart

解决方案


await不会“删除” then,但它允许以更方便的语法编写异步代码,例如 withthen和一种 replaces then。然后由编译器
await重写回。then

await推迟执行以下代码,直到等待的异步操作的结果完成并返回结果值。
结果值Future不再是 a,因此then()不可用。


推荐阅读