Javascript 如何使下面的“.then()”只触发一次?
在下面的代码中。我正在为Javascript 如何使下面的“.then()”只触发一次?,javascript,loops,promise,Javascript,Loops,Promise,在下面的代码中。我正在为formFields的属性运行一个循环。如您所见,我使用计数器仅在使用api.uploadFieldFile上载所有文件时运行this.updatePanCollection(): // formFields = { logo: { file: ... }, thumbnail: { file: ... } } let toUploadCount = 0 let uploadedCount = 0 Object.entries(formFields).
formFields
的属性运行一个循环。如您所见,我使用计数器仅在使用api.uploadFieldFile上载所有文件时运行this.updatePanCollection()
:
// 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()
中的代码运行了两次
如何更改此代码,使其只运行一次(在所有文件上载后)?使用Promise。所有
无需维护完成计数,如下所示:
Promise.all(
Object.entries(formFields).map(([key, upload]) => {
if (!upload || !upload.file) return;
return api.uploadFieldFile('logo', upload.file)
.then(downloadUrl => {
formFields[key] = downloadUrl
})
})
)
.then(() => {
// all have been uploaded
const updatePayload = {
id: this.currentPanoCollection.id,
data: formFields
}
return this.updatePanoCollection(updatePayload);
})
.then(() => {
// update is completed as well
})
.catch(err => this.handleError(err))
您指的是只运行一次的,第一次还是第二次?可能需要Promise.all
@CertainPerformance第二个。可能重复@MaazSyedAdeeb我不确定是否应该使用Promise.all
。我只回一个承诺。当文件还没有上传时,承诺就不会回来了。非常感谢。它起作用了!我很少使用Promise.all
。如何保证。所有的都会记录上传量?例如,它如何知道有1个或2个上载?它只需等待传递给解析的数组中的所有Promise
s,然后再解析自身。因此,例如,如果存在[,undefined]
,那么它将忽略未定义的,并等待单个承诺。