How do I make sure all promises are resolved properly? Here even after the execution of the function some statements are still getting printed(the ones where I have added comments). I feel getAllRecords is not completing promises properly. Where am I going wrong?
const getAllRecords = async (offset = 0) => {
return fetchRecord(offset, 10).then((resp) => {
console.log("Called fetchRecord")
if (resp.status === 'success') {
let responseData = resp.data
if (responseData.length === 0 {
return ({ status: 'success' })
}
return processData(responseData).then((updateResp) => {
if (updateResp.status === 'success') {
offset += 10
return getAllRecords(offset)
} else {
return ({ status: 'error' })
}
}).catch(err => {
return ({ status: 'error' })
})
} else {
return ({ status: 'error' })
}
}).catch(err => {
return ({ status: 'error' })
})
}
const mainFunc = async () => {
console.log('Inside mainFunc')
return new Promise((resolve, reject) => {
return firestore.getAllCities()
.then(async (cities) => {
return getAllRecords().then(getAllRecordsResponse => {
console.log("Called getAllRecords") //
if (getAllRecordsResponse.status === 'success') {
return getAllRecordsResponse
} else {
return reject({ status: 'error' })
}
}).then((getAllRecordsResponse) => {
let updateArray = []
console.log("Updating firestore db")
for (const city of cities) {
updateArray.push(firebaseDao.updatecityDoc(city))
}
return Promise.allSettled(updateArray).then((responseArr) => {
let errorArr = []
responseArr.map((item) =>
item.status === 'rejected' ? errorArr.push(item.reason) : null
)
if (!errorArr.length > 0) {
console.log("done processing") //
return resolve({ status: 'success' })
} else {
return resolve({ status: 'error' })
}
})
}).catch((err) => {
return resolve({ status: 'error' })
})
}).catch((err) => {
return resolve({ status: 'error' })
})
})
}
I am trying to fetch records from some other place in fetchRecord and processing the extracted data in processData. getAllRecords is a recursion because we cant get all the data at once, only 10 records can be extracted, so I am extracting the records until I get an empty response.
Where is the promise not getting handled properly is what I am not sure about. Am I missing out something here?
Is there a way to use promises only rather than async/await?