APIの結果が返ってきてから、次の処理を行ってね!
必要な情報が揃う前に勝手に先に進もうとしないでね!
ってことができるのがasync await
シンプルに言うとそういうことやろ?
なんか、他の人の記事の説明ばりわかりにくくない?
使い方
async getYourFavorites() {
//確実に処理を完了させたいAPI
const result= await axios.get("/api/hogehoge")
//上記のAPIの結果が出るのを待ってから行いたい処理
this.hoge(result)
},
例
ログインユーザーのお気に入り一覧を表示したい場合
async showYourFavorites() {
//ログインしているユーザーの情報を取得するAPI
const currentUser = await axios.get("/api/operator/info")
//そのユーザーがお気に入り登録しているレコードを取得するAPI
const favorites = await axios.get("/api/favorites/show?operatorId=" + currentUser.data.id)
//お気に入り登録されているレコードだけを一覧するメソッド
this.showFavorites()
},
こんな風にすれば上から順に走ってくれる。
ユーザーが誰かわかる前にお気に入り一覧を取得することはできないよな?
ちゃんとまこなりさんのfanzaのお気に入りリストを出してもらわないと困るわけや。
responsの中の特定の要素だけ使いたいときは?
.then(response => { return response.data })
みたいに書けばいい。
async getOperators(id) {
this.operators = await axios.get("/api/getoperators").then(response => {
return response.data
})//apiの結果の中かから[data]の中身だけを取得
if (this.$route.query.operator) {
this.detailSearchKey.operator = Number(id);
}//選択肢が完成したうえで、選択項目を動的に選択
},