- 需求的场景描述(希望解决的问题)下面是原来的代码 自己试着捣鼓 async await 无果 特来求大神助
- 希望提供的能力
doUpload: function() { // 选择图片
var that = this;
const filePath = that.data.images,
var imgFileId = [];
var cloudPath = [];
filePath.forEach((item, i) => {
cloudPath.push(util.formatTimestamp(new Date()) + filePath[i].match(/\.[^.]+?$/)[0])
})
filePath.forEach((item, i) => {
wx.cloud.uploadFile({
cloudPath: cloudPath[i],
filePath: item, // 文件路径
}).then(res => {
console.log(res)
imgFileId.push(res.fileID)
console.log(imgFileId)
})
})
return imgFileId;
},
submitForm: function(e) {
console.log(e)
var that = this;
let imgFileId = that.doUpload()
console.log(imgFileId)
//添加操作
let pudate = new Date();
const db = wx.cloud.database()
db.collection('forum').add({
data: {
content: e.detail.value.textarea,
pubdate: util.formatTime(pudate),
img: imgFileId,
title: e.detail.value.userTitle,
address: that.data.addressObj
}
}).then(res => {
wx.showToast({
title: "添加成功"
})
})
},
doUpload 里的遍历上传用Promise.all来改造一下即可
doUpload: function() { // 选择图片
var that = this;
const filePath = that.data.images
var cloudPath = [];
var promiseArry = [];
filePath.forEach((item, i) => {
cloudPath.push(util.formatTimestamp(new Date()) + '_' + i + filePath[i].match(/\.[^.]+?$/)[0])
})
filePath.forEach((item, i) => {
let wake = new Promise((resolve, reject) => {
wx.cloud.uploadFile({
cloudPath: cloudPath[i],
filePath: item, // 文件路径
success: function(res) {
resolve(res);
},
fail: function(res) {
reject(res);
}
})
})
promiseArry.push(wake);
})
return promiseArry
},
submitForm: function(e) {
var that = this;
var imgFileId = [];
Promise.all(that.doUpload()).then((res) => {
console.log(res)
res.forEach((item, i) => {
imgFileId.push(item.fileID)
})
let pudate = new Date();
const db = wx.cloud.database()
db.collection('forum').add({
data: {
content: e.detail.value.textarea,
pubdate: util.formatTime(pudate),
img: imgFileId,
title: e.detail.value.userTitle,
address: that.data.addressObj
}
}).then(res => {
wx.showToast({
title: "添加成功"
})
})
}).catch((error) => {
console.log(error)
})
//添加操作
},
成功了! ┭┮﹏┭┮ 是这样的吗?