I am facing an issue with using await/async in conjunction with Promise.all to retrieve arrays and proceed with the code. However, when I introduce a delay in the code, it seems like it's not functioning as expected. Below is my code snippet:
async getAllTheUnits() {
// obtain 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() {
// retrieve 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);
}
},
Below is a simplified function where these other functions are called:
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 mentioned earlier, if I introduce a settimeout
in the getAllTheWeeks
function to simulate a delay, the initUsersCourse
function proceeds without waiting and moves on to console.log('2')