0
0

More than 1 year has passed since last update.

async await multiple 自分の使う言語まとめ

Posted at

コンパイラの言うがままにasync awaitして結局同期的じゃんと言うコードを死ぬほどみてきた。
いいかげんそこそこ使いこなせる程度には知っておきたいね。

JavaScript

https://qiita.com/im36-123/items/c0678a46ee0f8e44e150
await Promise.all使う

function get(url) {
  return fetch(url);
}

async function fn() {
  const results = [];
  const urls = ['https://hoge/api', 'https://fuga/api'];
  for (const url of urls) {
    results.push(get(url));
  }
  console.log(await Promise.all(results));
}

Kotlin

https://stackoverflow.com/a/62966043/5598088
awaitAll使う

viewModelScope.launch {
    val a = async { firstUseCase.execute() }
    val b = async { secondUseCase.execute() }

    val (resA, resB) = awaitAll(a, b)

    //Use results 'resA' and 'resB' here
}

Python

asyncio.gather使う
https://stackoverflow.com/questions/34377319/combine-awaitables-like-promise-all

Dart

  final results = await Future.wait([
    task2(),
    task2(),
    task2(),
    task2(),
  ]);
  print(results);

Future<String> task2() async {
  String result;
  Duration sec3 = Duration(seconds: 3);
  await Future.delayed(sec3, () {
    result = 'task 2 data';
    print('Task 2 complete');
  });
  return result;
}

[task 2 data, task 2 data, task 2 data, task 2 data]
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