JavaScript 函数 return 值是来自 firestore 的未定义快照
JavaScript functions return value is undefined snapshot from firestore
我有以下代码。 return 函数 caloriex 的值始终未定义。
当我在 return 语句之前显示 returned 的值时,它显示了正确的值。但是当它从函数中 returned 时,它是未定义的。你能帮我解决这个问题吗?
function caloriex(calorie, meal){
let citiesRef = db.collection('food');
let query = citiesRef.where('category_out', '==', calorie).where('category_in', '==', meal).get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
}
var workingbalance = '';
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());//this result is fine
workingbalance = doc.data().id;
});
return workingbalance //returned VALUE is undefined
})
.catch(err => {
console.log('Error getting documents', err);
});
}
那是因为您从未 return 函数中的任何内容。它所做的只是 let
两个变量,然后有一堆内部函数的回调不会影响外部函数的 return 。语句 return workingbalance
只是 return 从您随后传递的内部 lambda 函数中获取该值 then
.
如果您想有效地使用异步编程,您将必须了解 JavaScript 中的 promise 和 promise 链是如何工作的。如果您想将 workingbalance
值提供给调用者,最好的办法是 return 整个 promise 链,并让调用者在该 promise 上使用 then
来获取该值。所以,它将是
return citiesRef.where(...).then(...).catch(...)
您的函数正在返回 [object promise],因为该 promise 尚未解决,您正在返回值。请使用 "await" 调用 Firestore 函数。
我有以下代码。 return 函数 caloriex 的值始终未定义。
当我在 return 语句之前显示 returned 的值时,它显示了正确的值。但是当它从函数中 returned 时,它是未定义的。你能帮我解决这个问题吗?
function caloriex(calorie, meal){
let citiesRef = db.collection('food');
let query = citiesRef.where('category_out', '==', calorie).where('category_in', '==', meal).get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
}
var workingbalance = '';
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());//this result is fine
workingbalance = doc.data().id;
});
return workingbalance //returned VALUE is undefined
})
.catch(err => {
console.log('Error getting documents', err);
});
}
那是因为您从未 return 函数中的任何内容。它所做的只是 let
两个变量,然后有一堆内部函数的回调不会影响外部函数的 return 。语句 return workingbalance
只是 return 从您随后传递的内部 lambda 函数中获取该值 then
.
如果您想有效地使用异步编程,您将必须了解 JavaScript 中的 promise 和 promise 链是如何工作的。如果您想将 workingbalance
值提供给调用者,最好的办法是 return 整个 promise 链,并让调用者在该 promise 上使用 then
来获取该值。所以,它将是
return citiesRef.where(...).then(...).catch(...)
您的函数正在返回 [object promise],因为该 promise 尚未解决,您正在返回值。请使用 "await" 调用 Firestore 函数。