JavaScript/TypeScriptでArray.mapとasync/awaitを使って非同期処理を行う方法
JavaScript/TypeScriptで Array.map と async/await を使って非同期処理を行う方法
Array.map と async/await を組み合わせる
Array.map
内で非同期処理を行う場合、async/await
を使って同期的に処理することができます。
例:
const urls = [
'https://www.google.com/',
'https://www.yahoo.co.jp/',
'https://www.bing.com/',
];
const responses = await Promise.all(urls.map(async (url) => {
const response = await fetch(url);
return response.text();
}));
console.log(responses); // 各URLのレスポンステキストが格納された配列
解説:
urls
という配列に、アクセスしたいURLを格納します。Promise.all
を使って、urls
の各要素に対してasync
関数を呼び出し、結果を配列に格納します。async
関数内で、fetch
を使ってURLにアクセスし、レスポンスを取得します。response.text()
でレスポンスのテキストを取得します。- 取得したテキストを
Promise
として返します。 Promise.all
の結果がresponses
に格納されます。
ポイント:
map
内でasync
関数を使用する場合は、await
を使って非同期処理の結果を待つ必要があります。Promise.all
は、すべての処理が完了するまで待機してから結果を返します。
async/await
を使う場合は、try/catch
を使ってエラー処理を行うことをおすすめします。- 並列処理を行いたい場合は、
Promise.all
以外にもmap
とasync/await
を組み合わせて実装することができます。
// 複数のURLのレスポンスを取得するサンプルコード
const urls = [
'https://www.google.com/',
'https://www.yahoo.co.jp/',
'https://www.bing.com/',
];
const getResponseText = async (url) => {
const response = await fetch(url);
return response.text();
};
const main = async () => {
const responses = await Promise.all(urls.map(getResponseText));
console.log(responses); // 各URLのレスポンステキストが格納された配列
};
main();
getResponseText
というasync
関数を定義します。この関数は、URLにアクセスし、レスポンスのテキストを取得します。main
というasync
関数を定義します。この関数は、urls
の各要素に対してgetResponseText
関数を呼び出し、結果を配列に格納します。main
関数を呼び出して、処理を実行します。
実行結果:
[
'<!DOCTYPE html>\n<html lang="en-US" dir="ltr">\n<head>\n<meta charset="utf-8">\n<title>Google</title>\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n<meta name="google" content="nositelinkssearchbox">\n<meta name="google-site-verification" content="7288815797101207460">\n<meta name="description" content="Search the world's information, including webpages, images, videos and more. Google has many features to help you find the information you need quickly and easily.">\n<meta name="keywords" content="google, search engine, information, webpages, images, videos">\n<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" media="all">\n<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Google+Sans:400,500,700&display=swap" media="all">\n<link rel="stylesheet" href="/css/fonts.css">\n<link rel="stylesheet" href="/css/core.css">\n<link rel="stylesheet" href="/css/homepage.css">\n<link rel="stylesheet" href="/css/public/js/homepage.css">\n<link rel="shortcut icon" href="https://www.google.com/favicon.ico">\n<style>\nbody, html, #viewport {\n height: 100%;\n margin: 0;\n padding: 0;\n width: 100%;\n}\n</style>\n<script nonce="...\n<\/script>\n<script nonce="...\n<\/script>\n<script>(function(){...})();\n<\/script>\n<script>(function(){...})();\n<\/script>\n<script>(function(){...})();\n<\/script>\n<script>(function(){...})();\n<\/script>\n<script nonce="...\n<\/script>\n<script nonce="...\n<\/script>\n<script nonce="...\n<\/script>\n<script nonce="...\n<\/script>\n<script>(function(){...})();\n<\/script>\n<\/head>\n<body class="hp hp-t h
Array.mapとasync/awaitの代わりにJavaScriptで非同期処理を行う方法
Promise.all
const urls = [
'https://www.google.com/',
'https://www.yahoo.co.jp/',
'https://www.bing.com/',
];
const responses = await Promise.all(urls.map(fetch));
console.log(responses); // 各URLのレスポンスオブジェクトが格納された配列
- 処理の順序は保証されません。
forループを使って、非同期処理を順番に実行することができます。
const urls = [
'https://www.google.com/',
'https://www.yahoo.co.jp/',
'https://www.bing.com/',
];
const responses = [];
for (const url of urls) {
const response = await fetch(url);
responses.push(response);
}
console.log(responses); // 各URLのレスポンスオブジェクトが格納された配列
- 処理の順序を制御することができます。
- すべての処理が完了するまで待機する必要はありません。
async/await
と for...of
を使って、非同期処理を順番に実行することができます。
const urls = [
'https://www.google.com/',
'https://www.yahoo.co.jp/',
'https://www.bing.com/',
];
async function main() {
const responses = [];
for (const url of urls) {
const response = await fetch(url);
responses.push(response);
}
console.log(responses); // 各URLのレスポンスオブジェクトが格納された配列
}
main();
RxJS は、非同期処理を扱うためのライブラリです。map
や pipe
などのオペレータを使って、非同期処理を簡単に記述することができます。
import { from, map, mergeAll } from 'rxjs';
const urls = [
'https://www.google.com/',
'https://www.yahoo.co.jp/',
'https://www.bing.com/',
];
const responses = from(urls).pipe(
map(fetch),
mergeAll()
);
responses.subscribe(console.log);
- 複雑な非同期処理を簡単に記述することができます。
- さまざまなオペレータを使って、処理を柔軟に制御することができます。
その他
上記以外にも、非同期処理を行う方法はいくつかあります。
- ジェネレータ
- async/await と Promise.all
- 処理の数が少ない場合は、
forループ
やasync/await
とfor...of
がおすすめです。 - 複雑な非同期処理を行う場合は、RxJS がおすすめです。
Array.mapとasync/await以外にも、JavaScriptで非同期処理を行う方法はいくつかあります。状況に合わせて、適切な方法を選びましょう。
javascript typescript promise