小程序request请求用promise公共方法以及调用

1.方法:

const baseUrl = 'https://api.it120.cc';
// 配置接口请求的公共方法
const http =({url ='',param ={},method='',header={}}={}) =>{
  wx.showLoading({
    title: '请求中,请耐心等待...',
  });
  let timeStart = Date.now();
  return new Promise((resolve,reject)=>{
    wx.request({
      url: getUrl(url),
      data:param,
      method: method,
      header:header,
      complete:(res)=>{
          wx.hideLoading();//慎用hideLoading,会关闭wx.showToast弹窗
          console.log(`耗时${Date.now() - timeStart}`);
          if(res.statusCode ==200){//请求成功
            resolve(res.data)
          }else{
            reject(res);
          }
      }
    })
  })
}
// 获取url
const getUrl = (url)=>{
  if(url.indexOf('://')== -1){
    url = baseUrl +url ;
  }
  return url;
}
//暴露出去调用的方法
 
const _api = (url,param ={},method,header)=>{
  return http({
    url,
    param,
    method:method?method:'get',
    header:header ? header : { "Content-Type": "application/json" },
  })
}
方法暴露出去
module.exports = {
  formatTime: formatTime,
  api:_api
}


2.掉用:

const until = require('../../utils/utils.js')

// 单个请求
until.api('/authorize',param,'post').then(res => {
    console.log("authorize:",res);
 }).catch(e => {
    console.log(e);
    wx.showToast({
        title: e.data.errMsg,
        icon: 'none',
        duration: 3000
    })
 })
// 一个页面多个请求
Promise.all([
  api.get('list'),
  api.get(`detail/${id}`)
]).then(result => {
  console.log(result)
}).catch(e => {
  console.log(e)
})
原文地址:https://www.cnblogs.com/changyuqing/p/12559736.html