18
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue.js】Async/awaitとaxiosによる非同期処理

Last updated at Posted at 2020-10-28

methodsに記述したaxiosによるHTTP通信の完了を待ってから残りの処理をしたい必要があったのですが、少し詰まったので記録として残しておきます。
※Async/awaitやaxiosについての説明記事ではありませんのでご了承ください

  mounted: {
    this.settingXxx();
  },
  methods: {
    fetchSample: async function(){
      let ret = null
      // 非同期処理を記述
      await axios.get('(url)', {
        .then((response) => {
          ret = response
        })
        .catch((error) => {
          this.errorMsg = 'Error! Could not reach the API. ' + error
          console.log(this.errorMsg)
        })
      return ret
    },
    settingXxx: async function(){
      // this.fetchSample()の実行が完了するまで待機
      let result = await this.fetchSample()
      console.log(result) //待機後の残りの処理を記述
    },
  }

fetchSample();によりPromiseオブジェクトが返され,
Promiseの状態が確定しその結果が返されるまで、JavaScriptを待機させます。

参考にさせていただいた記事

18
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?