導入
async, awaitとは何ぞやとなったので、自分なりにまとめてみた。
結論
結論は、非同期処理を行うものらしい。
Dart
ではFuture
型
javascript
ではPromise
型
が返り値となるみたい。
何じゃそれ。。
動かして理解してみる
import 'dart:io';
void main() {
ProcessTask();
}
void ProcessTask() async {
task1();
String task2Result = await task2();
task3(task2Result);
}
void task1() {
String result = 'task1 data';
print('task1 complate');
}
Future<String> task2() async {
Duration threeSeconds = Duration(seconds: 3);
String result = '';
sleep(Duration(seconds: 1));
print("start task2");
await Future.delayed(threeSeconds, () {
result = 'task2 data';
print('task2 complate');
});
return result;
}
void task3(String task2Data) {
String result = 'task3 data';
print('task3 complate with $task2Data');
}
実行結果は以下となった。
実行結果
task1 complate
start task2
task2 complate
task3 complate with task2 data
task1
→task2
→task3
の順に実行されている。
もう少し詳しく
ProcessTask()
void ProcessTask() async {
task1();
String task2Result = await task2();
task3(task2Result);
}
ProcessTask()
の横のasync
で非同期処理を行う関数であることを宣言している。
await
は処理を待ってもらう部分に記載し、Future
型でなければならない。
つまり、task2
はFuture
型で定義する必要がある。String
型ではerror
となる。
task2()
Future<String> task2() async {
Duration threeSeconds = Duration(seconds: 3);
String result = '';
sleep(Duration(seconds: 1));
print("start task2");
await Future.delayed(threeSeconds, () {
result = 'task2 data';
print('task2 complate');
});
return result;
}
task2()
関数の返り値はFuture<String>
となっている。<String>
は省略可。
task2()
もasync
の記載により非同期処理を行う関数なことがわかる。
await
の記載がある処理Future.delayed(...);
が完了してから、return result;
が実行される。
まとめ
async
の記載で、非同期処理を行うことを意味する。
await
の記載がある処理が完了するまで、次の処理は実行されない。