gpt4 book ai didi

asynchronous - 在Dart异步方法中,可以共享运行某些不共享任何依赖项的行吗?

转载 作者:行者123 更新时间:2023-12-03 02:53:46 24 4
gpt4 key购买 nike

假设您有一个异步方法主体,如下所示,该方法主体具有一个返回Future的方法调用,并在其后打印一个不需要该方法结果的输出。是否可以添加一些结构来使打印语句独立执行?还是这个语法糖迫使异步方法主体按顺序完全运行?

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';
}

最佳答案

编辑以跟进:

我不确定您到底要做什么,但是如果要在打印之前等待链完成,则必须执行以下操作:

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()并等待其返回“test1:done”,则必须等待它。
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()完成。

关于asynchronous - 在Dart异步方法中,可以共享运行某些不共享任何依赖项的行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950369/

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