【问题标题】:Can I commit a Firestore batch write without waiting?我可以在不等待的情况下提交 Firestore 批量写入吗?
【发布时间】: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


【解决方案1】:

如果您的 Cloud Function 不能正确处理所有异步工作(通常使用 Promise),则很有可能无法成功完成工作。

对于 HTTP 触发器,您只能在所有待处理的工作完成后向客户端发送最终响应。

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

您现在拥有的是一个未根据这些规则处理的“悬空”承诺。如果您使用 ESLint 或 TSLint 来检查您的代码,linter 可能会检测到这一点并抱怨它。

【讨论】:

  • 谢谢,道格。 “ ...您必须返回一个仅在该函数中的所有异步工作完成后才解析的承诺。”
  • 为了更清楚(以防其他人偶然发现),我在示例代码中添加了最终的 Promise 解决方案。
猜你喜欢
  • 2019-10-15
  • 2015-12-01
  • 2014-02-27
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
相关资源
最近更新 更多