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\$
10
  • \$\begingroup\$ Side note: You can't do multi-threading in JS environments. What you're doing here is parallel async calls. \$\endgroup\$ Commented Jul 19, 2019 at 12:24
  • 3
    \$\begingroup\$ Passing array of promises to Promise.all() is quite common...yes \$\endgroup\$
    – charlietfl
    Commented Jul 19, 2019 at 12:32
  • \$\begingroup\$ Title edited to avoid confusion relating to the definition of multi-threading. \$\endgroup\$
    – kanine
    Commented Jul 19, 2019 at 12:52
  • 2
    \$\begingroup\$ @NikKyriakides SharedArrayBuffers provide shared memory across workers. nodejs.org/api/… \$\endgroup\$
    – Blindman67
    Commented Jul 21, 2019 at 18:50
  • 1
    \$\begingroup\$ @Blindman67 I stand corrected \$\endgroup\$ Commented Jul 21, 2019 at 18:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.