async和await的執(zhí)行順序

首先貼一下教程:
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;
}

其中后面注釋的數(shù)字是我添加的,代表了輸出順序。
我看了下文檔,總結(jié)了一下,在dart遇到await語(yǔ)句的時(shí)候,如果這個(gè)await調(diào)用的函數(shù)里還調(diào)用了其他async函數(shù),比如上面的printDailyNewsDigest就又調(diào)用了gatherNewsReports,這時(shí)候printDailyNewsDigest會(huì)執(zhí)行到gatherNewsReports函數(shù)里的await語(yǔ)句之前的代碼,如果還有更多的await語(yǔ)句以此類推會(huì)一直執(zhí)行到最后一個(gè)async的await語(yǔ)句之前然后返回Future,然后執(zhí)行下面的非async部分的代碼,在執(zhí)行完以后會(huì)從最后一個(gè)await語(yǔ)句開(kāi)始執(zhí)行,然后就是上面的輸出順序。


如果理解的不正確歡迎指正

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容