繁体   English   中英

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

[英]In a Dart async method, can certain lines that don't share any dependencies be run asynchronously?

假设您有一个异步方法主体(如下所示),该方法主体具有一个返回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()完成。

这是因为在test2();之前await test2(); 执行将暂停,直到test2()返回的Future完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM