小程序 使用Promise封装request 接口请求

//httpService.js
const host = 'https://baidu.com/ceshi' // 接口请求的域名 // get请求使用 json对象转字符串 (formatParams ) const formatParams = (data) => { let arr = [] for (let name in data) { arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])) } return arr.join('&') } // 创建统一调用函数 const httpService = (url, params, method, loading = true) => { wx.showLoading({ title: '数据加载中...', }) let header = { "content-type": "application/json;charset=UTF-8" } return new Promise((resolve, reject) => { if (method === 'post') { wx.request({ url: host + url, data: params, method: method, header: header, timeout: 15000, complete: (res) => { resolve(res) wx.hideLoading() } }) } else if (method === 'get'){ wx.request({ url: host + url + '?' + formatParams(params), method: method, header: header, timeout: 15000, complete: (res) => { resolve(res) wx.hideLoading() } }) } }) }
module.exports = {
  httpService
}

//api.js 定义使用的接口api 实现统一管理
const { httpService } = require('httpService.js') /** * @name 医生/患者-我的提问详情页 * @param {*} params */ const questionSessionId = (sessionId, params) => { return httpService(`question/${sessionId}`, params, 'get') } module.exports = { questionSessionId }

页面使用

const { questionSessionId } = require('../../utils/api.js') // 引用
// 使用 方法一
 questionSessionId(id, data).then(res=>{
      console.log(res)
    }).catch(res=>{
      console.log(res)
    }
 )
// 使用方法二
async questionSession() {
      const getData= await questionSessionId(id, data)
      console.log(getData)
}     

 

 

 

posted @ 2020-08-28 16:19  悟空dong  阅读(1353)  评论(0编辑  收藏  举报