我正在使用 firebase 云功能和 firestore 交易来减少基于购买的产品的可用数量。部署时,它返回错误“错误 TS7030:并非所有代码路径都返回值”
这是代码
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
const db = admin.firestore()
exports.newOrder = functions.firestore
.document('orders/{orderId}')
.onCreate(async (snap, context) => {
try {
const data = snap.data();
if (data === undefined) return null
const itemList = data.list as Array<any>
const productId: Set<string> = new Set<string>();
itemList.forEach((item) => {
productId.add(item.id)
})
return db.runTransaction(async t => {
const promises: Promise<admin.firestore.DocumentSnapshot>[] = []
productId.forEach(i => {
const p = admin.firestore().doc('Products/' + i).get()
promises.push(p)
})
const docs=await Promise.all(promises)
docs.forEach(doc => {
if (!doc.exists) {
return Promise.reject("Product deleted")
}
})
itemList.forEach(j => {
if (j.variation === '-') {
const available = docs[j.id].get('available')
const needed = j.quantity
if (available < needed) {
return Promise.reject("Product out of stock")
}
}
else {
const variations = docs[j.id].get('variation') as Map<string, any>
for (const i in variations.keys) {
if (i === j.variation) {
const needed = j.quantity
const available = docs[j.id].get('variation').get(i).get('quantity')
if (available < needed) {
return Promise.reject("Product out of stock")
}
}
}
}
})
itemList.forEach(j => {
if (j.variation === '-') {
const available = docs[j.id].get('available')
const needed = j.quantity
t.update(db.doc('Products/' + j.id), { 'available': available - needed })
}
else {
const variations = docs[j.id].get('variation') as Map<string, any>
for (const i in variations.keys) {
if (i === j.variation) {
const needed = j.quantity
const available = docs[j.id].get('variation').get(i).get('quantity')
t.update(db.doc('Products/' + j.id), { [`variation.${i}.quantity`]: available - needed })
}
}
}
})
return Promise.resolve("Product quantity updated")
})
}
catch (error) {
console.log(`error ${error}`)
return null
}
});
这是部署时显示的错误
src/index.ts:30:30 - error TS7030: Not all code paths return a value.
30 docs.forEach(doc => {
~~~~~~~~
src/index.ts:35:34 - error TS7030: Not all code paths return a value.
35 itemList.forEach(j => {
~~~~~~
Found 2 error
如何解决该错误。
错误中提到的2个循环检查产品是否被删除以及产品是否缺货。如果它满足我想退出该函数的条件。请帮我。
错误消息告诉您有些函数并非在所有情况下都返回值。它甚至可以告诉我们哪些函数违反了这一要求。这是第一个错误:
src/index.ts:30:30 - error TS7030: Not all code paths return a value.
30 docs.forEach(doc => {
~~~~~~~~
它告诉您传递给 forEach 的函数有问题。
这是函数:
docs.forEach(doc => {
if (!doc.exists) {
return Promise.reject("Product deleted")
}
})
请注意,该函数在以下情况下不返回值:doc.exists
是真的。如果你不关心这种情况,直接返回null即可:
docs.forEach(doc => {
if (!doc.exists) {
return Promise.reject("Product deleted")
}
else {
return null
}
})
现在错误消失了,因为所有代码路径都返回一个值。您可以将相同的逻辑应用于其他错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)