Home > OS >  Call an async function with javascript
Call an async function with javascript

Time:12-04

I am trying to call an async function but I am getting an error

getUsersList.then is not a function

this is my code

async function getUsersList(db) {
  const userCol = collection(db, 'Users');
  const userSnapshot = await getDocs(userCol);
  const tempUserList = userSnapshot.docs.map(doc => doc.data());
  return tempUserList;
}


function App() {

  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);
  const auth = getAuth(app);


  var currentUser = auth.currentUser;

  if(currentUser != null){
    getUsersList(db).then((value) => {
  console.log(value);

});

I also tried using await getUsersList but got the following error

Unexpected reserved word 'await'

CodePudding user response:

async function getUsersList(db) {
  const userCol = collection(db, 'Users');
  const userSnapshot = await getDocs(userCol);
  const tempUserList = userSnapshot.docs.map(doc => doc.data());
  return tempUserList;
}


async function App() {

  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);
  const auth = getAuth(app);

  var currentUser = auth.currentUser;

  if(currentUser != null){
    const usersList = await getUsersList(db);
    console.log(usersList);
  }
}

CodePudding user response:

wrap inside async function may work :

async function getUsersList(db) {
  (async () => {
  const userCol = collection(db, 'Users');
  const userSnapshot = await getDocs(userCol);
  const tempUserList = userSnapshot.docs.map(doc => doc.data());
  return tempUserList;
  })()
}

  • Related