先上代码:如下,主要用promise.all来实现等待所有的请求完毕后关闭loading。
upImg(e) {
const index = e.currentTarget.dataset.index
const count = this.data.field_data[index].imgList.length;
this.setData({
field_data:this.data.field_data
})
console.log('count',count)
if(count===10){
wx.showToast({
title: '图片不能超过10张',
icon: 'none',
image: '',
duration: 1500,
mask: false,
success: (result)=>{
},
fail: ()=>{},
complete: ()=>{}
});
return
}
const that = this
wx.chooseImage({
count: 10 - count,
success: res => {
console.log('res图片',res)
// const list = [...this.data.imgList,...res.tempFilePaths]
// this.setData({
// imgList: list
// });
const header = {
'content-type': 'application/json'
}
header.authKey = wx.getStorageSync('authKey') || '';
header.sessionId = wx.getStorageSync('sessionId') || ''
wx.showLoading({
title: '图片加载中...',
mask: true,
success: (result)=>{
},
fail: ()=>{},
complete: ()=>{}
});
let allRequest = []
res.tempFilePaths.forEach((item,i,arr)=>{
allRequest[i] = new Promise((resolve)=>{
wx.uploadFile({
url:HTTP_REQUEST_URL+ '/api/common/upload',
filePath:item,
header:header,
name:'file',
formData: {},
success: (result)=>{
// console.log('上传成功',JSON.parse(result.data).data)
resolve(result)
const list = [...that.data.field_data[index].imgList,...[
{src:JSON.parse(result.data).data.url,title:JSON.parse(result.data).data.url.split('/')[6].substring(0,12)}
]
]
that.data.field_data[index].imgList = list
that.data.field_data[index].count = list.length
that.setData({field_data:that.data.field_data})
},
fail: (err)=>{
wx.hideLoading()
console.log('上传失败',err)
},
complete: ()=>{}
});
})
})
Promise.all(allRequest).then(res=>{
wx.hideLoading()
}
)
},
fail: err => {
wx.showToast({
title: err,
icon: 'none'
})
}
})
},