LoginSignup
0
0

More than 1 year has passed since last update.

[Dart]async awaitとは何ぞや

Last updated at Posted at 2022-03-09

導入

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

task1task2task3の順に実行されている。

もう少し詳しく

ProcessTask()

void ProcessTask() async {
  task1();
  String task2Result = await task2();
  task3(task2Result);
}

ProcessTask()の横のasyncで非同期処理を行う関数であることを宣言している。
awaitは処理を待ってもらう部分に記載し、Future型でなければならない。
つまり、task2Future型で定義する必要がある。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の記載がある処理が完了するまで、次の処理は実行されない。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0