Promise 配合 axios 使用

Promise是一个构造函数,自己身上有all、reject、resolve这几个眼熟的方法,原型上有then、catch等同样很眼熟的方法

很细致的Promise使用详解 自己脑补

vue 工程化的项目一般都会将请求函数进行组件化,

api 组件如下:

export default {
    
    fetchData (url, methods, datas) {
        return new Promise((resolve, reject) => {
          axios({
              url: url,
              method: methods,
              data: datas
            }).then((res) => {
              resolve(res)
            }).catch(function (error) {
              reject(error)
              // console.log(error);
            })
        })
    }
}

index.vue 调用

getData () {
     api.fetchData('https://www.apiopen.top/novelApi','get')
        .then(res=>{
             console.log(res.data);
         },error => {
             console.log(error)
     })
}
原文地址:https://www.cnblogs.com/ralapgao/p/10069677.html