async和await的执行顺序

作者: o动感超人o | 来源:发表于2018-12-10 18:07 被阅读4次

    首先贴一下教程:
    http://dart.goodev.org/tutorials/language/futures

    在async-and-await部分中,有一段代码,我修改了一下,如下

    // Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
    // for details. All rights reserved. Use of this source code is governed by a
    // BSD-style license that can be found in the LICENSE file.
    
    import 'dart:html';
    import 'dart:async';
    
    Future printDailyNewsDigest() async {
      print('printDailyNewsDigest 1');//1
      String news = await gatherNewsReports();
      print('printDailyNewsDigest 2');//7
      print(news);//8
    }
    
    main() {
      printDailyNewsDigest();
      printWinningLotteryNumbers();//3
      printWeatherForecast();//4
      printBaseballScore();//5
    }
    
    printWinningLotteryNumbers() {
      print('Winning lotto numbers: [23, 63, 87, 26, 2]');
    }
    
    printWeatherForecast() {
      print('Tomorrow\'s forecast: 70F, sunny.');
    }
    
    printBaseballScore() {
      print('Baseball score: Red Sox 10, Yankees 0');
    }
    
    // Imagine that this function is more complex and slow. :)
    Future gatherNewsReports() async {
      print('gatherNewsReports1');//2
      String path = 'https://www.dartlang.org/f/dailyNewsDigest.txt';
      var result = await HttpRequest.getString(path);
      print('gatherNewsReports2');//6
      return result;
    }
    

    其中后面注释的数字是我添加的,代表了输出顺序。
    我看了下文档,总结了一下,在dart遇到await语句的时候,如果这个await调用的函数里还调用了其他async函数,比如上面的printDailyNewsDigest就又调用了gatherNewsReports,这时候printDailyNewsDigest会执行到gatherNewsReports函数里的await语句之前的代码,如果还有更多的await语句以此类推会一直执行到最后一个async的await语句之前然后返回Future,然后执行下面的非async部分的代码,在执行完以后会从最后一个await语句开始执行,然后就是上面的输出顺序。


    如果理解的不正确欢迎指正

    相关文章

      网友评论

        本文标题:async和await的执行顺序

        本文链接:https://www.haomeiwen.com/subject/dpedhqtx.html