I know promise.all()
expects an array of promises.
But, is it possible to do something like below? If no, please suggest a workaround.
It's not recommended to use await
inside for
loop. That's why I am pushing in an array and doing promise.all()
on that.
var functionArray = [];
for (let i = 0; i < jobs.length; i += 1) {
...
if (params.origins !== '' && params.destinations !== '') {
functionArray.push(async function() {
response = await getDistance(params.origins, params.destinations);
if (response.error) {
// handle error
return null
} else {
distances = response.data.rows[0].elements.map((el, index) => {
el.emp_id = empIdOrder[index];
return el;
});
sortedDistances = sortDistance(distances);
return formatDataForInsert(jobs[i].job_id, sortedDistances);
}
});
}
}
var dataToBeinserted = await Promise.all(functionArray); // return an array with results
It doesn't work as expected.
await Promise.all(functionArray);
always return [ [AsyncFunction], [AsyncFunction] ]
.
Shouldn't it be resolved instead?