1. Background
Mini program development often encounters the problem of requesting results based on the network and then continuing to process the next business operation. The code is as follows:
//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)
}
})
Characteristics of this generation: nested layers, low readability of logic, and difficult to maintain. The solution is to use new Promise((resolve, reject) => {}) which can be solved using asynchronous sequential execution.
2. Code examples
//1、分步获取接口数据
new Promise((resolve, reject) => {
return resolve(that.getCollectListData());//获取接口数据1
}).then(res => {
return that.getDoctorListData();//获取接口数据2
}).then(res => {
that.initData();//显示数据
}).catch(err => {
});
First request function code example
//请求接口函数
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;
},
second function data
//
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;
},