解决地狱式回掉函数代码运行慢,如果需要等多个回掉函数都返回数据,在最后使用,这样一层一层的执行,最后一次成功再使用所有数据,需要很长时间。
wx.getImageInfo({
src: 'https://static.bzsh.souqu.net/201912131335284d73d4300.png',
success: (res) => {
let headUrl = res.path;
wx.getImageInfo({
src: 'https://static.bzsh.souqu.net/20191213134501407262999.png',
success: (res) => {
let bodyUrl = res.path;
wx.getImageInfo({
src: 'https://static.bzsh.souqu.net/201912131349457c9c08795.png',
success: (res) => {
let legUrl = res.path;
wx.getImageInfo({
src: 'https://static.bzsh.souqu.net/201912131317157945f1577.png',
success: (res) => {
let eyeUrl = res.path;
this.setData({
graph: {
type: 'peopleImg',
headUrl,
bodyUrl,
legUrl,
eyeUrl,
}
});
}
})
}
})
}
})
}
})
promise.all可以让多个回掉函数同时执行,等所有的回调函数都成功返回数据了再执行其他代码
loadImage:function (item) {
return new Promise((resolve) => {
wx.getImageInfo({
src: item.person_image_info.file_path,
success: (res) => {
item.drawUrl = res.path;
resolve(item); //回掉函数的返回值
}
});
})
},
addImg: function () {
let imageArr = this.data.peopleList;
let arr = [];
imageArr.forEach( (item)=>{
arr.push(this.loadImage(item));
});
Promise.all(arr).then((newList) => {
this.setData({
graph: {
type: 'peopleImg',
peopleList: newList,
}
});
});
//Promise.all(arr).then((参数) => {})中的参数就是所有回调函数的返回值,是个数组