zoukankan      html  css  js  c++  java
  • 小程序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)
    })
  • 相关阅读:
    c# 使用Selenium模拟登录和操作数据的学习记录【续】
    c# 使用Selenium模拟登录和操作数据的学习记录
    使用bat一键安装mysql
    使用c#程序 添加iis网站目录的用户权限
    NOIp游记
    线规集合
    背包规划集合
    阴间扫描线
    11.30数学集合
    高精度运算
  • 原文地址:https://www.cnblogs.com/changyuqing/p/12559736.html
Copyright © 2011-2022 走看看