[英]AngularJS and the effect of the promise value when calling a local function - undefined
[英]Undefined value when calling function in Firestore
我正在使用 Firestore,并编写了以下代码:
export function getAllServices(uid) {
let services = [];
firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
snapshot.docs.forEach(doc => {
services.push(doc.data());
console.log(services);
return services;
})
})
}
function 工作 b/c console.log 返回我想要的数组。 但是,当我这样称呼它时
const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
const services = getAllServices(uid);
console.log(services);
控制台日志始终返回未定义。 有任何想法吗?
鉴于您使用asynchronous
标记了您的问题,您似乎已经知道问题的原因。 数据从 Firestore 异步加载,并return services;
绝不会从getAllServices
返回值。 返回getAllServices
的唯一方法是在其中的第一级代码中,但此时您的then()
回调还不会被调用。
解决方案是从then()
回调内部冒泡值,并将其作为 promise 返回。
export function getAllServices(uid) {
return firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
let services = [];
snapshot.docs.forEach(doc => {
services.push(doc.data());
})
return services;
})
}
然后您可以调用getAllServices
并使用如下结果:
const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
getAllServices(uid).then(function(services) {
console.log(services);
});
您可以使用现代 JavaScript 的async
和await
关键字使上述内容看起来更熟悉
export async function getAllServices(uid) {
let services = [];
return firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
let services = [];
snapshot.docs.forEach(doc => {
services.push(doc.data());
})
return services;
})
}
const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
let services = await getAllServices(uid);
console.log(services);
请记住,这都是(非常可读的)语法糖,并且数据仍在幕后异步检索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.