博客
关于我
如何使用Promise封装wx.request()
阅读量:615 次
发布时间:2019-03-13

本文共 1363 字,大约阅读时间需要 4 分钟。

1、在根目录下创建一个文档,例如创建一个http文档,在文档内写入三个js文件,分别为api.js文件、fetch.js文件以及http.js文件

在这里插入图片描述

2、在fetch.js中用promise对wx.request()进行封装

//module.exports=(url,method,data)=>{   //let p=new Promise ((resolve,reject)=>{   //      wx.request({   //            url:url,//接口路径   //            method:method,//使用的方式 例如 get方式   //            data:Object.assign({},data), //所传递的数据   //            header:{'Content-Type': 'application/text'},   //            success(res){   //                 resolve(res)  //             },  //            fail(err){  //                 reject(err)  //            }  //       })  //   })  //     return p;  //   }

3、在api.js中封装具体的接口路径

// module.exports={//    banner:'/home/swiperdata',//此路径仅供参考// }

4、在http.js,根据当前环境,设置相应的baseurl,引入fetch中封装好的promise请求,封装基础的get\post\put\upload等请求方法,设置请求体,带上token和异常处理等;

设置对应的方法导出;

// const  api=require('./api')  // const  fetch=require('./fetch')  // let  baseUrl;   //接口的公共部分  //轮播的请求函数  // function banner(){  //      return fetch(baseUrl+api.banner,"get",{})  // }  //导出接口函数  // module.exports={  //      banner  // }

5、在全局app.js中导入http,注册到根组件

// var http=require('./http/http')  // App({  // http:http,     // })

6、在具体页面中,并使用;

//获取应用实例  // const app=getApp();  // Page({  // data:{  //   list:[]  // }  // onLoad: function(){  // app.http.banner().then((res)=>{  // this.setData({  // list: res.data.list  // })  // })  // )

转载地址:http://qhtaz.baihongyu.com/

你可能感兴趣的文章
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>