I have function fetchData
that accepts an integer id
and calls promise with random resolve time
const promise = (ms) => new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, ms);
});
const fetchData= async (id) => {
const ms = Math.floor(Math.random() * 1000);
const ans = await promise(ms);
return ans
}
I have an array of ids = [1, 2, 3, 4, 5]
I need to call the fetchData
with all ids
in parallel and reorder the ids
array based on the time taken to resolve
I tried this
const main = async () => {
const ids = [1, 2, 3, 4, 5];
const promises = ids.map(id => fetchData(id));
const result = await Promise.all(promises);
console.log(result)
}
but it doesn’t show which one resolved first
I added this to make it more clear
Note: I don’t have access to edit fetchData
function and the promises only return "Done". I can only edit the main
function
4
Answers
You need to return 2 parameters from your function,
One will be the real answers and the second will be the time it took.
To measure the time, you can use
performance.now
native call.When you have results of this 2 tuples you can sort them be processed time.
I did it just for fun:
I added a callback function to
fetchData
so it could record the order that the promises return in.Here’s how you might do it from
main
function. I assume you’re interested in the processing times only, but it can be easily extended to return the actual fetched data as well.It’s done in 1 line without changing anything else: