首页 > 解决方案 > 试图理解 async 然后

问题描述

我写了这个简单的代码:

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

我理解错了什么?

标签: flutterdart

解决方案


您对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

推荐阅读