flutter - 试图理解 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
我理解错了什么?
解决方案
您对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
推荐阅读
- c++ - 标准对成员变量声明的顺序有何规定?
- apache-spark - 将结构数组扩展为 PySpark 中的列
- python - Python MongoDB 聚合并仅获取有限数量的文档
- vue.js - vue-i18n:带有 html 标签的组件插值
- ansible - curl POST -o 下载一个 zip 文件但 ansible 没有?
- ms-access - 使用任务调度程序运行 MS Access mdb
- java - java中的初学者刽子手游戏
- javascript - API 的集成与单元测试
- xaml - UWP XAML 文本框自定义
- javascript - 无法保存到整数和浮点数的 Firestore 数组