将异步函数结果分配给变量

时间:2020-06-16 06:46:40

标签: javascript firebase google-cloud-firestore async-await

我正在获取一个Firestore集合,其文档ID与docs数据合并,如下所示:

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函数中添加异步功能,很难理解为什么

我想将结果转换为变量,我尝试实现this question's解决方案,但无法使其正常工作。

我已经尝试过了:

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]
});

我想要的是拥有一个包含用户的变量(在// [THIS SCOPE]上),然后循环这些值并做一些“事情”

1 个答案:

答案 0 :(得分:1)

您可以将异步过程提取到一个独立的函数中。

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;
}

希望它可以为您提供帮助。