promise封装步骤

60 阅读1分钟
  • 第一步建立http文件夹 再建立http.js
  • 第二步封装具体的请求,建立api.js
  • 第三步在login页面调用接口:
function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)//执行函数,obj为传入函数的参数
    })
  }
}



module.exports = {
    wxPromisify: wxPromisify
}

重新定义函数后的使用方法如下代码所示:

getUserInfo()
.then(res =>{
    console.log(res)    
})

request({
    url: 'https://xindongpeixun.com/auth/news/page',
    method: 'GET',
    header:{
        'content-type': 'json'
    }
}).then(res => {   
    console.log(res.data.data.records) 
    getUserInfo()
    .then(res =>{
        console.log(res)    
    })                    
})