If anyone found this question is a dup, please comment a link to that, or any suggestions would be appreciated.
The request is to fetch data bases on an array of
id
.Function
getWorkhoursById()
has already been configured withaxios
, including the Bearer and clientId, so I want to reuse it for this purpose.So, now the
result
will be filled up with array ofids
for each fetch, but it takes some time to reach the final value. My question is how can I retrieve the final value ofarrayOfIds
(with all the ids in the last iteration) to perform the next task.I tried the
for loop
method - check the last value of it, but I would like to do this in a more proper, asynchronous way.
const arrayOfIds = [];
let result = [];
const foo = (item, index, id) => {
return new Promise((resolve, reject) => {
setTimeout(async () => {
const data = await getWorkhoursById(id);
if (data.length === 0) result.push(item);
resolve();
}, 1000 * (index + 1)); // force async function to execute in order
});
};
const bar = () => {
return arrayOfIds.forEach(async (item, index) => {
names(item, index, id).then(() => {
console.log(result, "result"); // <- need the last value of result
});
});
};