簡體   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