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)
    })
  • 相关阅读:
    java生成json字符串的方法
    JSON的三种解析方式
    Android Studio你不知道的调试技巧
    Android 打开URL
    build.gradle中引入jar
    Spark RDD/Core 编程 API入门系列之map、filter、textFile、cache、对Job输出结果进行升和降序、union、groupByKey、join、reduce、lookup(一)
    NovaMind *的安装、和谐破解到永久使用
    小Q书桌的下载、安装和使用
    作业提交过程分析(源码)
    SparkContext的初始化过程分析(源码)
  • 原文地址:https://www.cnblogs.com/changyuqing/p/12559736.html
Copyright © 2011-2022 走看看