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);

  const syncThing = await Promise.all(arrayTestResult);

  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';

<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>


  • \$\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 '19 at 12:24
  • 3
    \$\begingroup\$ Passing array of promises to Promise.all() is quite common...yes \$\endgroup\$ – charlietfl Jul 19 '19 at 12:32
  • \$\begingroup\$ Title edited to avoid confusion relating to the definition of multi-threading. \$\endgroup\$ – kanine Jul 19 '19 at 12:52
  • 2
    \$\begingroup\$ @NikKyriakides SharedArrayBuffers provide shared memory across workers. nodejs.org/api/… \$\endgroup\$ – Blindman67 Jul 21 '19 at 18:50
  • 1
    \$\begingroup\$ @Blindman67 I stand corrected \$\endgroup\$ – Nik Kyriakides Jul 21 '19 at 18:51

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.