我对如何在没有嵌套承诺的情况下重构我的代码进行读写有点困惑。在编写对象时,如果该对象设置了标志,我想使用新计数更新其"相关"对象。我有两个问题。
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);
});
}
});
变化:
- 在顶层进行链式的,而不是越来越深的嵌套。
- 返回嵌套的承诺,以便它们正确链接。
- 将错误处理程序合并到一个
.catch()