假设你有一个异步方法体,如下所示,带有一个返回Future的方法调用,以及一个不需要该方法结果的打印。是否可以添加一些结构来使print语句独立执行?或者这个语法糖是否强制异步方法体完全顺序运行?
Future<String> test2() {
Completer c = new Completer();
new Timer(new Duration(seconds: 2), () {
c.complete('test2: done');
});
return c.future;
}
Future<String> test1() async {
String result = await test2();
print(result);
// Why is this not executed immediately before test2 call completes?
print('hello');
return 'test1: done';
}
void main() {
test1().then((result) => print(result));
}
跟进:我在下面添加了一个test1()的重写,它连接了异步方法调用。我真的在如何使用异步语法糖来简化这种用例。我怎么能用新语法重写这个块?
Future<String> test1() async {
test2().then((result) {
print(result);
test2().then((result) {
print(result);
});
});
// This should be executed immediately before
// the test2() chain completes.
print('hello');
return 'test1: done';
}
答案 0 :(得分:2)
编辑后续跟踪:
我不确定你想要做什么,但如果你想在打印东西之前等待链完成,那么你需要做什么:
Future<String> test1() async {
String result;
var result1 = await test2();
print("Printing result1 $result1 ; this will wait for the first call to test2() to finish to print");
var result2 = await test2();
print("Printing result2 $result2 ; this will wait for the second call to test2() to print");
// This should be executed immediately before
// the test2() chain completes.
print('hello');
return 'test1: done';
}
现在,如果你打电话给test1()
并等待它返回&#34; test1:done&#34;你必须等待它。
main() async {
var result = await test1();
print(result); // should print "hello" and "test1: done"
}
如果您想独立于之前的结果执行代码,请不要使用await
关键字。
Future<String> test1() async {
test2().then((String result) => print(result)); // the call to test2 will not stop the flow of test1(). Once test2's execution will be finished, it'll print the result asynchronously
// This will be printed without having to wait for test2 to finish.
print('hello');
return 'test1: done';
}
关键字await
会使流量停止,直到test2()
完成。
答案 1 :(得分:1)
这是因为await
之前的test2();
。执行暂停,直到test2()
返回的Future完成。