im looking for a way to asynchronous iterate over an array and update a variable and in the end return this variable.
export const test = async(
...
): Promise<number> => {
let highestAmount = 0;
for (const entry of entries) {
const check = async () => {
let amount = 0
try {
newAmount = await getAmount(entry);
} catch (e) {
return;
}
if (newAmount > amount ) {
highestAmount = newAmount;
}
}
check()
}
return highestAmount;
}
In this current state i only get 0's back because the function doesnt wait for its finish. Is there a way that the function only returns if all processes inside the for are finished ? Lets say the getAmount(entry) function takes 1 second to finish then i have to wait around entries.length seconds. Im trying to find a way to execute this in 1 second so getAmount is called for every entry asynchronously => function returns highest number
CodePudding user response:
Lets say the
getAmount(entry)
function takes 1 second to finish then i have to wait aroundentries.length
seconds. I'm trying to find a way to execute this in 1 second
If you have five calls that take one second you can't execute and return a value from the function in one second.
Is there a way that the function only returns if all processes inside the for are finished?
Yes. This, however, is possible.
If you map
over your array to produce an array of promises that you can await
with Promise.all
, you can then use Math.max
to get the highest number from that array.
// Generate a random number
function rnd() {
return Math.floor(Math.random() * (100 - 0) 0);
}
// Mock API call which returns the number passed into
// multiplied by an erratic method of
// creating a new random number
function getAmount(el) {
return new Promise(res => {
setTimeout(() => res((el - rnd()) rnd()), 500);
});
}
// Create an array of promises, await them to resolve
// and then return the highest number
async function getData(entries) {
const promises = entries.map(el => getAmount(el));
const data = await Promise.all(promises);
console.log(data);
return Math.max(...data);
}
// Await the promise that `getData` returns
// and log the result
async function main(entries) {
console.log(await getData(entries));
}
const entries = [1, 2, 3, 4, 5];
main(entries);
CodePudding user response:
There are a couple of things missing to make this wait:
- Put an async in the parent function
- Put an await in the check function call
For example:
export const test = async (
...
): Promise<number> => {
//...
await check();
};
There might also be ways to make these async calls run in parallel.