以下代码循环遍历formFields
数组。有两种类型的字段:包含要上传的文件和不包含文件的字段。我记得排队"排队"字段和"完成"那些,所以我知道何时更新表格
const payload = {}
const fields = {
queued: [],
finished: []
}
formFields.forEach(field => {
fields.queued.push(field)
if (hasUploadFiles(field)) { // FOR FILE INPUTS
utils.mapCallPromise(field.value, file => {
api.uploadPhoto(file, field).then(uploadedPhoto => {
payload[field.name] = uploadedPhoto
fields.finished.push(field)
})
})
} else { // FOR NORMAL INPUTS
payload[field.name] = field.value
fields.finished.push(field)
}
})
if (fields.queued.length === fields.finished.length) {
console.log('use the payload to update the form')
}
问题是api.uploadPhoto
在 if (fields.queued.length === fields.finished.length)
之后触发。
如何修改代码,以便在if (fields.queued.length === fields.finished.length)
完成后触发api.uploadPhoto
?
更新
这是api.uploadPhoto
和utils.mapCallPromise
:
api.uploadPhoto = async (file = {}, field = {}) => {
if (utils.includes(api.usServers, api.env)) {
return await usImageUpload.toFirebase(file, field)
} else {
return await cnImageUpload.toQCloud(file, field.userId, field.sizes)
}
}
utils.mapCallPromise = (object, callback) => {
return new Promise((resolve, reject) => {
return Array.prototype.slice.call(object).map(value => {
return resolve(callback(value))
})
})
},
答案 0 :(得分:1)
使用Promise.all和数组映射方法,您可以执行以下操作
Promise.all(formFields.map(field => {
if (hasUploadFiles(field)) { // FOR FILE INPUTS
return api.uploadPhoto(file, field).then(uploadedPhoto => {
return {field, uploadedPhoto};
});
} else { // FOR NORMAL INPUTS
return {field};
}
})).then(results => {
//results is an array of objects that are either {field, uploadedPhoto} or just {field}
});