我对如何在没有嵌套承诺的情况下重构我的代码进行读写有点困惑。在写入对象时,如果该对象设置了标志,我想用新计数更新其“相关”对象。我有两个问题。
1)来自read然后写入的嵌套Promise。 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);
})
};
});
另外,它要我退货......没有?
答案 0 :(得分:5)
您可以使用链接并消除一些嵌套。
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()