Javascript 将异步函数结果分配给变量
我得到一个firestore集合,其文档id与文档数据合并,如下所示:Javascript 将异步函数结果分配给变量,javascript,firebase,google-cloud-firestore,async-await,Javascript,Firebase,Google Cloud Firestore,Async Await,我得到一个firestore集合,其文档id与文档数据合并,如下所示: async function getUsers() { const users = []; fb_db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { const data = { ...doc.data(), ...{ id: doc.
async function getUsers() {
const users = [];
fb_db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
const data = { ...doc.data(), ...{ id: doc.id }};
if ( data.userid !== undefined && data.userid.length > 0 ) users.push(data);
});
return users;
});
}
//this is the other question's solution
const asyncExample = async () => {
const result = await getUsers()
return result
}
据我所知,我应该向getUsers函数添加async,但我显然不完全理解为什么
我想把结果变成一个变量,我已经试着实现了这个解决方案,但我无法让它工作
我试过这个:
document.addEventListener('DOMContentLoaded', function(e) {
someFunction();
// this doesn't log anything but undefined
;(async () => {
const users = await asyncExample()
console.log(users)
})()
//obviously this doesn't work either, it just logs a promise
the_users = getUsers();
console.log(the_users);
//[THIS SCOPE]
});
我想要的是有一个包含用户的变量(在//[这个范围]),然后循环值并执行“一些操作”您可以将异步进程提取到一个独立的函数中
async function getQuerySnapshot() {
return fb_db.collection("users").get(); // here return a promise
}
async function getUsers() {
const querySnapshot = await getQuerySnapshot();
const users = [];
querySnapshot.forEach((doc) => {
const data = { ...doc.data(), ...{ id: doc.id }};
if ( data.userid !== undefined && data.userid.length > 0 ) users.push(data);
});
// variable users is the value you want to get
return users;
}
希望它能帮助您。您不会从
getUsers()
返回任何内容。它应该是return fb_db.collection(…
我不知道为什么,但是像您描述的那样分离函数使它工作起来了现在可以工作了,想解释一下原因吗?@AlanVelasco,因为正如我所说,你以前没有从函数返回任何东西。这一个返回了。但是分离函数没有意义。@GuyIncognito如果你没有提取异步,那么如何直接返回承诺值,如上所述?我唯一的方法是使用回调来处理提取的使用rs.@GuyIncognito,我仍然很困惑,因为你说我没有从getUsers()返回任何东西,但我确实返回了,有一行“return users;”。@fengxhconst querySnapshot=wait fb_db.collection(“users”)。get()
和你的完全一样。