小程序request封装成promise


const api_url="...";//接口地址

function fetchRequest(url, method, data) {
  return new Promise((resolve, reject)=>{
    wx.request({
      url: `${api_url}${url}`,
      data: data,
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'content-type': 'application/json',
      }, // 设置请求的 header
      success: ((res)=>{
        if(res.statusCode=== 200) {
          //成功
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: function() {
        // fail
        console.log('fail')
      },
      complete: function() {
        // complete
        console.log('complete')
      }
    })
  })
}
//例举了3中常用的get,post,delete请求方式,其他的请求方式同理
const requestGet = (url, data)=> fetchRequest(url, 'GET', data);
const requestPost=(url, data)=> fetchRequest(url, 'POST', data);
const requestDelete=(url, data)=> fetchRequest(url, 'DELETE', data);
module.exports = {
  requestGet,
  requestPost,
  requestDelete
}

你可能感兴趣的:(小程序request封装成promise)