then method and catch method in vue

1. The then() method is executed asynchronously.

It means: after the method before .then() is executed, then execute the program inside then(), so as to avoid the problem that the data is not obtained. Usually used after ajax request

2. The catch() method prevents the system from crashing due to errors

In the program logic, it is necessary to add a catch method to the logical code fragments that are prone to problems. This can catch errors, but it will not affect the operation of the entire program;

3. Examples

        1. Write two parameters in then(). The first one is the callback method when it succeeds. By default, the successful data is passed to this method, and the other
is the failed method and failed data.
 

<script>
export default {
  name: 'demo',
  data() {
    return {}
  },
  methods: {
    testDemo(data) {
      // ajax请求
      testAjax(url, params).then(data => {
        // 处理成功
        console.log(data)
      }, data => {
        // 处理失败
        console.log(data)
      })
    }
  }
}
</script>

2. In general, in order not to report an error, .catch() will be called after then(), which is equivalent to try{}catch(e){}, which can be understood as omitting try()

<script>
export default {
  name: 'demo',
  data() {
    return {}
  },
  methods: {
    testDemo(data) {
      // ajax请求
      testAjax(url, params).then(data => {
        // 处理成功
        console.log(data)
      }).catch(err => {
        // 报错
        console.log(err)
      })
    }
  }
}
</script>

3. The main difference: if an exception is thrown in the first function of then, it can be caught by the catch later, but not in the second function of then. Therefore, it is recommended to always use the catch method instead of the second parameter of the then method.

Reference: then method and catch method in vue_jokester961's blog-CSDN blog_The usage of then in vue

Guess you like

Origin blog.csdn.net/coinisi_li/article/details/127239434