【问题标题】:Dart avait Future, postpone just certain line of code and execute the restDart avait Future,仅推迟某行代码并执行其余代码
【发布时间】:2021-11-29 18:35:57
【问题描述】:

想要推迟某些代码行,使用 await Future 并且效果很好,问题是它推迟了它之后的所有代码,我需要它推迟某些代码行,同时继续执行其余的代码立即编码

void main() async {
  for (int i = 0; i < 5; i++) {
       await Future.delayed(Duration(seconds: 1));
    //postpone just next line or few lines of code
    print('postpone this line of code ${i + 1}');
    print('postpone me too');
  }
  //should execute without being postponed
  print('continue imediately without being postponed by await Future');
}

这可以通过 await Future 或其他一些功能实现吗?

【问题讨论】:

    标签: dart async-await future


    【解决方案1】:

    await 它是注册Future.then 回调的语法糖。使用await 的目的是更容易让所有后续代码等待Future 完成。如果这不是你想要的,你可以直接使用Future.then:

    void main() {
      for (int i = 0; i < 5; i++) {
        Future.delayed(const Duration(seconds: 1)).then((_) {
          print('postpone this line of code ${i + 1}');
          print('postpone me too');
        });
      }
      print('continue immediately without being postponed by await Future');
    }
    

    由于Future.delayed有回调,你也可以完全跳过then:

    void main() {
      for (int i = 0; i < 5; i++) {
        Future.delayed(const Duration(seconds: 1), () {
          print('postpone this line of code ${i + 1}');
          print('postpone me too');
        });
      }
      print('continue immediately without being postponed by await Future');
    }
    

    如果你不使用创建的未来做任何事情,这相当于使用Timer:

    import 'dart:async' show Timer;
    void main() {
      for (int i = 0; i < 5; i++) {
        Timer(const Duration(seconds: 1), () {
          print('postpone this line of code ${i + 1}');
          print('postpone me too');
        });
      }
      print('continue immediately without being postponed by await Future');
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多