I'm trying to run a function after 1) all loops are completed and 2) all database calls within those loops are completed.
My database call functions (segmentDatabaseCall
and stepDatabaseCall
) all take some arguments, resolve a Promise and send the data once the call is complete. This is a (very) simplified version of my code:
let localData = {}
segmentDatabaseCall(argument) // Call the database
.then(segmentResult => { // Returns trip segments (array of objects)
$.each(segmentResult, (segmentIndex, segmentValue) => { // For each trip segment...
localData['something'] = segmentValue.something // Add some data to local data
stepDatabaseCall(segmentValue.segment_id) // Call the database once per trip segment...
.then(stepResult => { // Returns trip steps (array of objects)
$.each(stepResult, (stepIndex, stepValue) => { // For each trip step...
localData['something'][i]['something_else'] = stepValue.something_else // Add some data to local data
// THIS DOESN'T WORK
const segsDone = segmentIndex >= segmentResult.length - 1;
const stepsDone = stepIndex >= stepResult.length - 1;
if (segsDone && stepsDone) {
// This if statement runs before all calls are finished 1 out of 3 times roughly
}
})
})
})
})
Database call:
function databaseCall (argument) {
return new Promise((resolve, reject) => {
$.ajax({
url: $phpUrl,
type: 'post',
data: {
'argument': argument
}
})
.done (function (data) {
var resultJson = JSON.parse(data)
resolve(resultJson)
})
.fail (function (error) {
reject(error)
})
})
}
I've tried using the answer here, but it runs before all calls are finished 1 in 3 times. I must be missing some counter there?
I also think there's a way to do this using Promise maps, but I can't get my head around it.