gpt4 book ai didi

flutter - 试图理解 async 然后

转载 作者:行者123 更新时间:2023-12-03 04:40:42 26 4
gpt4 key购买 nike

我写了这个简单的代码:

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不只是强制函数暂停。它使整个应用程序暂停,其中包括未决的 future 。
相反,请使用 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

关于flutter - 试图理解 async 然后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63310372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com