promise的正確寫法(規避回撥地獄的寫法)
阿新 • • 發佈:2021-10-09
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') } } }