【发布时间】:2018-02-28 16:59:10
【问题描述】:
概述
我想在云函数中创建一些文档引用并将它们返回以在另一个文档中使用。我的应用程序对时间要求很高,因此我不想在返回引用之前等待批处理提交。
当前解决方案
我目前在一个 Cloud Function 中创建引用和目标文档,然后提交整个批次。这使我的代码重复,因为我还需要在其他地方创建这些引用。
我的问题
如果我从 batch.commit() 中省略了 .then,我是否可以直接将引用传回并让 Cloud Firestore 自行编写文档?
我创建了这个测试脚本,它可以工作。这种方法有问题吗,还是我应该一直等待批处理完成写入,然后再继续执行代码?
我的示例代码
// Set the data to be written
let myData = {test: '123'};
// Create the document references and return them for future processing
let docRefs = writeData(myData);
// Write these references to a master document
myDoc = {
name: 'A document containing references to other documents',
doc0Ref: docRefs[0],
doc1Ref: docRefs[1],
doc2Ref: docRefs[2]
}
return db.collection('masterCollection').add(myDoc).then(response => {
console.log('Success');
return Promise.resolve();
}).catch(err => {
console.error(err);
return Promise.reject(err);
});
// Create the batch and write the data
function writeData(myData) {
let batch = firestore.batch();
let doc1Ref = firestore.collection('test').doc();
let doc2Ref = firestore.collection('test').doc();
let doc3Ref = firestore.collection('test').doc();
console.log(`doc1Ref: ${doc1Ref.id}, doc2Ref: ${doc2Ref.id}, doc3Ref = ${doc3Ref.id}`);
batch.set(doc1Ref, myData);
batch.set(doc2Ref, myData);
batch.set(doc3Ref, myData);
batch.commit(); // No .then to wait for the batch to be written
return [doc1Ref, doc2Ref, doc3Ref];
}
【问题讨论】:
-
请详细说明此代码运行的上下文。这是在 Cloud Functions 中吗?其他环境?调用这个
writeData函数后你打算做什么? -
我添加了一些进一步的代码并在问题中澄清,这是在 Cloud Functions for Firebase 中运行的。
标签: node.js firebase google-cloud-functions google-cloud-firestore firebase-admin