Dart の非同期処理/同期処理

2020年4月26日 Posted by PURGE

thenを使用 (非同期処理)

void main(){
  print("A");
  futurePrint(Duration(milliseconds: 2000), "B")
    .then((status) => print(status));
  print("C");
  futurePrint(Duration(milliseconds: 1000), "D")
    .then((status) => print(status));
  print("E");
}

Future<String> futurePrint(Duration dr, String msg){
  return Future.delayed(dr).then((onValue) => msg);
}

//A
//C
//E
//D
//B

async / await を使用 (同期処理)

void main() async {
  print("A");
  await futurePrint(Duration(milliseconds: 2000), "B")
    .then((status) => print(status));
  print("C");
  await futurePrint(Duration(milliseconds: 1000), "D")
    .then((status) => print(status));
  print("E");
}

Future<String> futurePrint(Duration dr, String msg){
  return Future.delayed(dr).then((onValue) => msg);
}

//A
//B
//C
//D
//E

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です