首先貼一下教程:
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í)行,然后就是上面的輸出順序。
如果理解的不正確歡迎指正