Home > Back-end >  Wait for code to complete using await/async and promise
Wait for code to complete using await/async and promise

Time:08-04

I am trying to use await/async along with Promise.all to get some arrays and then move on with the code but when I simulate a delay in the code it appears to not be working. My code is below

    async getAllTheUnits() {
        // get all units
        console.log('allunits called 1')
        let unitRef = db.collection('units')
        try {
            let allUnitsSnapShot = await unitRef.get()
            await Promise.all(allUnitsSnapShot.docs.map(async (doc) => {
                let u = doc.data()
                u.id = doc.id
                await this.allOfTheUnits.push(u)
            }))
            console.log('allunits called 2 ', this.allOfTheUnits.length)
        }
        catch (err) {
            console.log('Error getting all the units', err);
        }
    },
    async getAllTheWeeks() {
        // get all weeks
        console.log('allweeks called 1')
        let weekRef = db.collection('weeks')
        try {
            let allWeeksSnapShot = await weekRef.get()
            await Promise.all(allWeeksSnapShot.docs.map(async (doc) => {
                let w = doc.data()
                w.id = doc.id
                await this.allOfTheWeeks.push(w)
            }))
            console.log('allweeks called 2 ', this.allOfTheWeeks.length)
        }
        catch (err) {
            console.log('Error getting all the weeks', err);
        }
    },

Here is a simplified function where I call these other functions

    async initUsersCourse() {

        console.log('1')

        await this.getAllTheUnits()
        await this.getAllTheWeeks()

        console.log('2')

        const allUnits = this.allOfTheUnits
        const allWeeks = this.allOfTheWeeks

        console.log('3')
        console.log('allUnits ', Array.isArray(allUnits), allUnits.length   )
        console.log('allWeeks ', Array.isArray(allWeeks), allWeeks.length)
    }

As stated above. If I put in a settimeout in the getAllTheWeeks function to simulate a delay the initUsersCourse function does not wait and moves on to console.log('2')

CodePudding user response:

your function must return a promise, you need resolve the promise after the timeout finish :

async getAllTheWeeks() {
    return new Promise( resolve => setTimeout( resolve, 2000 ) );
}

for your specific code problem, Promise.all want an array of promise, so the function you give at your allWeeksSnapShot.docs.map must return a promise, that's not currently the case so promise.all must return directly

  • Related