コンパイラの言うがままに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]