promise的正确写法(规避回调地狱的写法)

import axios from 'axios'
export default {
  mounted() {
    // this.getTodos().then((res) => {
    //   console.log('todos', res.data)
    //   this.getComments().then((res) => {
    //     console.log('comments', res.data)
    //     this.getAlbums().then((res) => {
    //       console.log('albums', res.data)
    //     })
    //   })
    // })
    // 当请求之间有依赖关系时,上面的写法会导致回调地狱,推荐下面的写法
    this.getTodos()
      .then((res) => {
        console.log('todos', res.data)
        return this.getComments()
      })
      .then((res) => {
        console.log('comments', res.data)
        return this.getAlbums()
      })
      .then((res) => {
        console.log('albums', res.data)
      })
  },
  methods: {
    getTodos() {
      return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
    },
    getComments() {
      return axios.get('https://jsonplaceholder.typicode.com/comments?_limit=5')
    },
    getAlbums() {
      return axios.get('https://jsonplaceholder.typicode.com/albums?_limit=5')
    }
  }
}

 

上一篇:理解Promise


下一篇:promise基本实现