0
0

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 1 year has passed since last update.

JavaScriptのasync/awaitとPromiseチェーンのthen()について

Last updated at Posted at 2023-01-27
sample.vue
//省略
<script>
export default {
    //省略
    methods: {    
        method1(){
            this.$axios.$get('URL1',{params: {param1: param1, param2: param2})
            .then(response => {
                // 最初の処理
                this.item1 = response.item1
                this.item2 = response.item2
                //if文も可能
                if(response.data != null){
                    this.data = response.data
                }
                return this.$axios.$get('URL2');
            })
            .then(secondResponse => {
                // 2つ目の処理
                return this.$axios.$get('URL3');
            })
            .then(thirdResponse => {
                // 3つ目の処理
            })
            .catch(error => {
                this.message = error
                //errorも複数行可能
            })
            .finally(() => {
                //hogehoge
            })
        }
    }
}
</script>

<script>
export default {
    //省略
    methods: {   
    // async awaitを使用する場合
    async getData(){
        try{
            const response = await this.$axios.$get('URL',{params: {param1: param1, param2: param2})
            if(response != null){
                this.item1 = response.item1
                this.item2 = response.item2
            }
        } catch (error) {
        // handle the error
      }
    async getSomeData() {
      try {
        const [response1, response2] = await Promise.all([
          this.$axios.$get('/api/v1/example/1'),
          this.$axios.$get('/api/v1/example/2')
        ]);
        console.log(response1)
        console.log(response2)
      } catch (error) {
        // handle the error
      }
    }
   }
}
</script>
0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?