【问题标题】:Trying to understand async and then试图理解 async 然后
【发布时间】:2020-08-07 23:34:14
【问题描述】:

我写了这个简单的代码:

import 'dart:io';

Future<int> f() async {
  await Future.delayed(Duration(seconds: 3));
  return 7;
}

void main() {
  int a = 3;
  Future b = f();
  b.then( (value) {
    print("b value received: " + value.toString() );
    a = value;
  } );
  print(a);
  sleep(const Duration(seconds: 6));
  print(a);
  print("end");
}

函数 f,在辅助线程中,将在 3 秒后返回 7。

在主函数中,我有一个 = 3。

调用函数 f,返回 Future b。

当 b 收到它的值时,我会打印“b value received”,并将 b 赋值给 a。

我所期待的:

- print a -> 3
- after 3 seconds:
- b value received: 7
- after more 3 seconds:
- print a -> 7
- print end

我收到了什么:

- 3
- (after 6 seconds)
- 3
- end
- b value received: 7

我理解错了什么?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您对async 工作方式的期望是正确的。
    问题不在于async,而在于您使用sleep 对其进行了测试。

    sleep 不只是强制函数暂停。它使整个应用程序暂停,包括未决的期货。

    改为使用await Future.delayed:

    import 'dart:io';
    
    Future<int> f() async {
      await Future.delayed(Duration(seconds: 3));
      return 7;
    }
    
    void main() async {
      int a = 3;
      Future b = f();
      b.then((value) {
        print("b value received: " + value.toString());
        a = value;
      });
      print(a);
      await Future.delayed(const Duration(seconds: 6));
      print(a);
      print("end");
    }
    

    哪个打印:

    3
    b value received: 7
    7
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      相关资源
      最近更新 更多