如何在Cloud Functions Firestore中处理读写操作

我有点困惑如何重构我的代码读取和写入没有嵌套的承诺。 在写入对象时,如果该对象有一个标志设置,我想用新的计数来更新它的“相关”对象。 我有两个问题。

1)嵌套承诺从读取然后写入。 2)我应该回来什么

exports.updateRelationshipCounts = functions.firestore .document('masterProduct/{nfCode}').onWrite((event) => { //on writing of record: var newProduct = event.data.data(); if (newProduct.isGlutenFreeYN === 'Y') { console.log('Gluten Free'); //Update GF count in the Brand Object: var db = admin.firestore(); var docRef = db.collection("masterBrand").doc(newProduct.brandNFCode); var doc = docRef.get() .then(doc => { doc.glutenFreeCount = doc.glutenFreeCount + 1 docRef.set(newProduct.brand) .then(function () { console.log("Document successfully written!"); }) .catch(function (error) { console.error("Error writing document: ", error); }); }) .catch(err => { console.log('Error getting document', err); }) }; }); 

再加上它要我回来的东西…无?

你可以使用链接并消除一些嵌套。

 exports.updateRelationshipCounts = functions.firestore .document('masterProduct/{nfCode}').onWrite((event) => { //on writing of record: var newProduct = event.data.data(); if (newProduct.isGlutenFreeYN === 'Y') { console.log('Gluten Free'); //Update GF count in the Brand Object: var db = admin.firestore(); var docRef = db.collection("masterBrand").doc(newProduct.brandNFCode); docRef.get().then(doc => { doc.glutenFreeCount = doc.glutenFreeCount + 1 return docRef.set(newProduct.brand); }).then(() => { console.log("document successfully written); }).catch(err => { // will log all errors in one place console.log(err); }); } }); 

变化:

  1. 顶级链条,而不是更深和更深的嵌套。
  2. 返回嵌套的承诺,以便它们正确链接。
  3. 将error handling程序合并到一个.catch()