Назначить результат функции asyn c переменной - PullRequest
0 голосов
/ 16 июня 2020

Я получаю коллекцию firestore с идентификатором документов, объединенным с данными документов, например:

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
}

Насколько я понимаю, я должен добавить asyn c в getUsers, сложно, очевидно, не до конца понимаю, почему

Я хочу получить результат в переменной, я пытался реализовать решение этого вопроса, но я не могу получить его работа.

Я пробовал это:

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

Я хочу иметь переменную, содержащую пользователей (в // [ЭТОЙ ОБЪЕМ]), а затем l oop значения и "кое-что"

1 Ответ

1 голос
/ 16 июня 2020

вы можете извлечь асинхронный c процесс в независимую функцию.

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

Может вам это поможет.

...