我可以在不等待的情况下提交Firestore批量写入吗?

时间:2018-02-28 16:59:11

标签: node.js firebase google-cloud-functions google-cloud-firestore firebase-admin

概述

我想在Cloud Function中创建一些文档引用,并返回它们以在另一个文档中使用。我的应用程序是时间关键的,所以我不想在返回引用之前等待批处理提交。

当前解决方案

我目前在一个Cloud Function中创建引用和目标文档,然后提交整个批处理。这使得我的代码重复,因为我还需要在其他地方创建这些引用。

我的问题

如果我省略了.then中的batch.commit(),我可以直接将参考文件直接传递回来,让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];
}

1 个答案:

答案 0 :(得分:0)

如果你的云功能没有正确处理所有异步工作(通常是使用promises),那么工作很可能无法成功完成。

对于HTTP触发器,您必须在所有待处理的工作完成后才将最终响应发送到客户端

对于所有其他类型的触发器,您必须返回一个仅在该函数中的所有异步工作完成后才能解析的promise。

你现在所拥有的是一个“悬挂”的承诺,这些承诺没有按照这些规则处理。如果您正在使用ESLint或TSLint检查您的代码,那么linter可能会检测到并抱怨它。