【Vue.js】Promise.allで並列処理を管理。
はじめに
個人の勉強用アプリで並列処理を書く機会があったので備忘録として残します。
サンプルコード
以下はAPI通信を行い、全てのレスポンスが返ったら処理を行うサンプルコードです。 レスポンスには各リクエストの結果が配列となって返ってきます。
<template> <v-container> <v-row> <v-col cols="6"> {{ data1 }} </v-col> <v-col cols="6"> {{ data2 }} </v-col> </v-row> </v-container> </template> <script> import axios from "axios"; export default { name: "Index", data() { return { data1: "", data2: "" }; }, async created() { let vm = this; await Promise.all([ axios.get(`APIのエンドポイント1`), axios.get(`APIのエンドポイント2`), ]) .then((response) => { vm.data1 = response[0].data; vm.data1 = response[1].data; }) .catch(function (response) { console.log(response); }); }, }; </script>
全ての通信が終わるのを待つ必要がない場合は単純に以下のように書く感じでOKです。
axios.get(`APIのエンドポイント1`) .then((response) => {}) .catch((response) => {}) axios.get(`APIのエンドポイント2`) .then((response) => {}) .catch((response) => {})
おわりに
Promise系は他にも多数あるのでいずれしっかり学んでいきたいですね。