I need to make an unknown number of api calls, up to 5 max probably. But most samples I've seen show only a couple of async calls so are effectively hard coded to the number of calls being made.
This is what I came up with as a demonstration, it has an array with three sleep times in it to simulate an API call of variable duration. The main function should wait until all three calls are finished.
It works but is this the right way to go about it?
const sleep = async(milliseconds) => {
await sleepMain(milliseconds);
console.log(`Awake: ${milliseconds}`);
let value = {
sleep: milliseconds
};
return value;
}
const sleepMain = (milliseconds) => {
console.log(`Sleeping ${milliseconds}`)
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
const asyncTest = async() => {
arrayTest = [1000, 3000, 5000];
arrayTestResult = Array();
arrayTest.forEach(function(element) {
console.log('Start Sleep: ' + element);
arrayTestResult.push(sleep(element));
});
const syncThing = await Promise.all(arrayTestResult);
console.log(syncThing);
return syncThing;
}
const main = async() => {
console.log('Start Main');
document.getElementById('message').innerHTML = 'Running...';
await asyncTest();
console.log('Finish Main');
document.getElementById('message').innerHTML = 'Finished - See Console Log';
}
main();
<h1>Multi Thread Async Test</h1>
<p>Runs the array of sleep lengths (in async) and completes when all done</p>
<p>sleep and sleepMain are used to simulate an API call of variable response time</p>
<h2 id='message'></h2>