如何解决Firebase函数成功完成1-2次,然后引发错误:无法修改已提交的WriteBatch
我使用批处理写入firestore
,而我的firebase-functions
代码总是在第一次尝试时成功执行。
i functions: Beginning execution of "myFunction"
i functions: Finished "myFunction" in ~1s
i functions: Beginning execution of "myFunction"
API fetch ...
Amount of records to process: 3600
filled batch (amount of writes: 490)
filled batch (amount of writes: 490)
...
All batches commited to Firebase
imported batch
imported batch
...
i functions: Finished "myFunction" in ~33s
该错误总是在函数的第二次或第三次执行时发生,并显示以下错误消息:
Unhandled error Error: Cannot modify a WriteBatch that has been committed.
- 我创建了一个具有批次的数组,并向每个批次传递了490次写入。
- 我执行
await Promise.all()
内的每个提交操作
我想我的错误是在步骤2中。我尝试了Promise链和异步等待:
异步/等待:
try {
await Promise.all(batches.map(batch => batch.commit()))
console.log('All batches commited to Firebase')
} catch (error) {
console.log(error)
}
承诺链:
await Promise.all(batches.map(batch => {
return batch.commit().then(function () {
console.log("imported batch")
});
}))
.then(console.log('All batches commited to Firebase'))
.catch(err => console.log(err))
batchs数组本身就是这样创建的,我在循环中多次调用以下函数:
function useBatches(collectionRef,action,type,docId,data) {
const docRef = collectionRef.doc(docId);
switch(action) {
case 'delete':
batches[batchIndex].delete(docRef);
break;
case 'update':
batches[batchIndex].update(docRef,data);
break;
case 'set':
batches[batchIndex].set(docRef,data);
break;
}
batchSizeCounter++;
totalWritesTodo--
// create batches
if (batchSizeCounter === BATCH_SIZE) {
console.log(`filled batch (amount of writes: ${batchSizeCounter})`)
batches.push(db.batch());
batchIndex++;
batchSizeCounter = 0;
}
// inform about last batch was filled
if (totalWritesTodo === 0) {
console.log(`filled batch (amount of writes: ${batchSizeCounter})`)
return;
}
}
非常感谢您的帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。