3
\$\begingroup\$

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>

https://jsfiddle.net/kanineAU/yv21Leqf/

\$\endgroup\$

migrated from stackoverflow.com Jul 21 at 11:21

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ Side note: You can't do multi-threading in JS environments. What you're doing here is parallel async calls. \$\endgroup\$ – Nik Kyriakides Jul 19 at 12:24
  • 3
    \$\begingroup\$ Passing array of promises to Promise.all() is quite common...yes \$\endgroup\$ – charlietfl Jul 19 at 12:32
  • \$\begingroup\$ Title edited to avoid confusion relating to the definition of multi-threading. \$\endgroup\$ – kanine Jul 19 at 12:52
  • \$\begingroup\$ can use async.queue if you want (and like the async library) \$\endgroup\$ – Aritra Chakraborty Jul 19 at 12:55
  • 1
    \$\begingroup\$ @NikKyriakides SharedArrayBuffers provide shared memory across workers. nodejs.org/api/… \$\endgroup\$ – Blindman67 Jul 21 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.