内蒙古电子商务网站,做行业网站投入,房地产销售述职报告,网站建设论文的中期报告一、背景 小程序开发经常遇到根据网络请求结果#xff0c;然后继续 处理下一步业务操作#xff0c;代码如下#xff1a;
//1第一个请求
wx.request({url:https://example.com/api/,data:data,success:function(res){//2第二个请求 wx.request({url:http…
一、背景 小程序开发经常遇到根据网络请求结果然后继续 处理下一步业务操作代码如下
//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;},