Search code examples
javascriptasync-awaites6-promise

How to use promise in order to wait for a function to execute


I have an async piece of javascript code that need to execute and then the next statements can be executed

function getEventData() {
            return new Promise(resolve => {
              eventList.forEach((event) => {
                db.collection('Events').doc(event)?.collection('registeredStudents')?.get()
                .then((querySnapshot) => {
                  eventData.push({"id": event, "number": querySnapshot.size})
                })
              })
              resolve();
            })
          }
          getEventData().then(console.log(eventData))

eventList is an array with 17 elements and it list through the database around 17 times, that is inefficient but I had no choice so had to do like that. Anyways in the console I get an empty array logged. How do I solve that. PS: I am new to async javascript and promises.


Solution

  • The correct way to deal with your problem is not using new Promise with resolve, yet by using async await. When you await a promise, it waits for it to resolve and returns the result (not a promise!) before continuing to the next line. A function awaiting a promise returns a promise when called. Promise.all combines multiple promises to one, so you can wait for multiple promises to resolve all at once, and have them run at the same time (async).

    async function getEventData(eventList) {
        try {
            const eventData = [];
    
            await Promise.all(eventList.map(async event => {
                const querySnapshot = await db.collection('Events').doc(event)?.collection('registeredStudents')?.get();
                eventData.push({"id": event, "number": querySnapshot.size});
            }));
            
            console.log(eventData)
        } catch (exception) {
          // error handling
        }
    }