【发布时间】:2018-11-22 14:44:47
【问题描述】:
在下面的代码中。我正在为formFields 的属性运行一个循环。如您所见,我使用计数器仅在使用api.uploadFieldFile 上传所有文件时才运行this.updatePanoCollection():
// formFields = { logo: { file: ... }, thumbnail: { file: ... } }
let toUploadCount = 0
let uploadedCount = 0
Object.entries(formFields).forEach(([key, upload]) => {
if (!upload || !upload.file) return
toUploadCount++
api.uploadFieldFile('logo', upload.file).then(downloadUrl => {
formFields[key] = downloadUrl
const updatePayload = {
id: this.currentPanoCollection.id,
data: formFields
}
uploadedCount++
if (toUploadCount === uploadedCount) {
// This only runs once right now
return this.updatePanoCollection(updatePayload)
}
}).then(() => {
// But this runs twice. It should only run once.
}).catch(err => this.handleError(err))
})
现在的问题是.then() 中的代码运行了两次。
如何更改此代码使其仅运行一次(在所有文件上传后)?
【问题讨论】:
-
你指的是哪个
then你只想运行一次,第一次还是第二次?可能想要Promise.all -
@CertainPerformance 第二个。
-
@MaazSyedAdeeb 我不确定是否应该使用
promise.all。我只回报一个承诺。当文件尚未上传时,promise 不会返回。
标签: javascript loops promise