一、背景
小程序开发经常遇到根据网络请求结果,然后继续 处理下一步业务操作,代码如下:
- //1第一个请求
- wx.request({
- url:"https://example.com/api/",
- data:data,
- success:function(res){
-
- //2第二个请求
- wx.request({
- url:"https://example.com/api/",
- data:data,
- success:function(res){
-
- //3第三个请求
- wx.request({
- url:"https://example.com/api/",
- data:data,
- success:function(res){
- console.log(res.data)
- },
- fail:function(err){
- console.log(err)
- }
- },
- fail:function(err){
- console.log(err)
- }
- })
-
-
- },
- fail:function(err){
- console.log(err)
- }
- })
这段代特点:层层嵌套,逻辑负责可读性低,不易维护。解决方案使用 new Promise((resolve, reject) => {})可使用异步顺序执行来解决。
二、代码示例
- //1、分步获取接口数据
- new Promise((resolve, reject) => {
-
- return resolve(that.getCollectListData());//获取接口数据1
-
- }).then(res => {
-
- return that.getDoctorListData();//获取接口数据2
-
- }).then(res => {
-
-
- that.initData();//显示数据
- }).catch(err => {
-
- });
第一个请求函数代码示例
-
-
- //请求接口函数
- getCollectListData() {
-
- var that = this;
- var usId = 'userId';
-
- var result = new Promise(function (resolve, reject) {
- //对象
- let obj = {
- method: "GET",
- showLoading: false,
- data: {
- 'userId': usId
- },
- url: '/de/api/eva',
- };
-
- httpUtilsDeal.request(obj).then(res => {
-
- if (res.data.code == 200) {
-
- resolve(res);
- }
- }).catch(err => {
- reject(err)
- });
- })
- return result;
- },
-
第二个函数数据
-
- //
- getDoctorListData() {
-
- var that = this;
- var usId = 'userId';
-
- var result = new Promise(function (resolve, reject) {
-
- //对象
- let obj = {
- method: "GET",
- showLoading: false,
- data: {
- 'readRecord.izCollect': 1,
- 'readRecord.userId': usId
- },
- url: '/iu/api/k/listPage',
- };
-
- httpUtilsDeal.request(obj).then(res => {
-
- if (res.data.code == 200) {
- resolve(res);
- }
- }).catch(err => {
- reject(err)
- });
- })
-
- return result;
- },
-