非同期処理を行うときはできるだけ早く処理を完了させたい。
というわけで、さっさと済ませられる処理は個別でやってしまいたいし、並列実行できるものはできるだけ並列実行する。
並列実行しない場合
1
2
3
4
5
6
|
const fc = async() => {
const hogeRes = await axios.get("https://httpbin.org/status/200");
const fooRes = await axios.get("https://httpbin.org/status/201");
console.log(hogeRes.status);
console.log(fooRes.status);
}
|
並列実行する場合
1
2
3
4
5
6
7
8
|
const fc = async() => {
const urls = ["https://httpbin.org/status/200", "https://httpbin.org/status/201"];
const [hogeRes, fooRes] = await Promise.all(
urls.map((url) => axios.get(url));
);
console.log(hogeRes.status);
console.log(fooRes.status);
}
|
参考:async/await で複数の非同期処理を待つときに注意したいこと - Qiita
先に終わった処理の値を先に使いたい場合
1
2
3
4
5
6
7
8
|
const fc = async() => {
const urls = ["https://httpbin.org/status/200", "https://httpbin.org/status/201"];
const promiseArray = urls.map(async (url) => {
const res = await axios.get(url);
console.log(res.status);
})
await Promise.all(promiseArray);
}
|
ただ、それぞれの値に違う処理を加えたい場合もある。
その場合は、素直に並べて記述すればいい(JSではデフォルトで並列実行なので)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
const fc = () => {
hoge();
foo();
}
const hoge = async() => {
const res = await axios.get("https://httpbin.org/status/200");
console.log('hoge: ' + res.status);
}
const foo = async() => {
const res = await axios.get("https://httpbin.org/status/201");
console.log('foo: ' + res.status);
}
|
またはコールバック関数を使うようにして、
1
2
3
4
5
6
7
8
|
const fc = () => {
axios.get("https://httpbin.org/status/200").then((res) => {
console.log('hoge: ' + res.status);
};
axios.get("https://httpbin.org/status/201").then((res) => {
console.log('foo: ' + res.status);
}
}
|