Dart async proc

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Dart async proc相关的知识,希望对你有一定的参考价值。

//dart

import ‘dart:io‘;
import ‘dart:async‘;

Future printDailyNewsDigest1() {
print(‘A:‘);
File file = new File("dailyNewsDigest.txt");
Future future = file.readAsString();
return future;
}

Future printDailyNewsDigest2(String content) {
print(‘A:$content‘);
File file = new File("dailyNewsDigest.txt");
Future future = file.readAsString();
return future;
}

Future printDailyNewsDigest3(String content) {
print(‘A:$content‘);
File file = new File("dailyNewsDigest.txt");
Future future = file.readAsString();
return future;
}

Future printDailyNewsDigest_1() {
print(‘B:‘);
File file = new File("dailyNewsDigest.txt");
Future future = file.readAsString();
return future;
}

Future printDailyNewsDigest_2() {
print(‘B:‘);
File file = new File("dailyNewsDigest.txt");
Future future = file.readAsString();
return future;
}

Future printDailyNewsDigest_3() {
print(‘B:‘);
File file = new File("dailyNewsDigest.txt");
Future future = file.readAsString();
return future;
}

void chooseBestResponse(List ress) {
print(ress.length);
String B1 = ress[0];
String B2 = ress[1];
String B3 = ress[2];
print(‘B:[1]$B1‘);
print(‘B:[2]$B2‘);
print(‘B:[3]$B3‘);
}

void main() {
printDailyNewsDigest1().then(printDailyNewsDigest2)
.then(printDailyNewsDigest3)
.then((content)=>print(‘A:$content‘))
.catchError((e)=>handleError(e));


Future.wait([printDailyNewsDigest_1(), printDailyNewsDigest_2(), printDailyNewsDigest_3()])
.then(chooseBestResponse)
.catchError((e)=>handleError(e));
}

//执行结果

C:\Dart-pro\demo\4>dart future.dart
A:
B:
B:
B:
A:Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow‘s forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0
3
B:[1]Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow‘s forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0
B:[2]Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow‘s forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0
B:[3]Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow‘s forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0
A:Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow‘s forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0
A:Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow‘s forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0

Finally:

异步执行

printDailyNewsDigest1执行后,立即执行Future.wait

printDailyNewsDigest_1(), printDailyNewsDigest_2(), printDailyNewsDigest_3()执行完后,进入回调过程

回调过程首先进入printDailyNewsDigest1的回调,然后进入Future.then,然后进入printDailyNewsDigest2回调,然后进入printDailyNewsDigest3回调。

Dart 的异步处理过程不太好用,要用最好还是一个future一个then回调来用,因为它的回调时间你可能把握不住!

不过,单线程的Dart给了你异步的能力,你还能要求什么呢。

开整吧,祝你好运!

以上是关于Dart async proc的主要内容,如果未能解决你的问题,请参考以下文章

Dart async proc

Future<void> async 与 Dart 中的简单 void async

Dart:在循环中使用 Async 和 Await

Flutter/Dart 中的 Future<void>, async, await, then, catchError

Flutter之异步操作async原理Future本质

Flutter之异步操作async原理Future本质