Skip to content

Instantly share code, notes, and snippets.

@tappoz
Created November 19, 2019 11:55
Show Gist options
  • Save tappoz/a8d3293cf88db99e44bd1d883d279de5 to your computer and use it in GitHub Desktop.
Save tappoz/a8d3293cf88db99e44bd1d883d279de5 to your computer and use it in GitHub Desktop.
An example on how to execute parallel Javascript promises with Promise.all

Promise.all example

const sleepPromise = (millis) => {
  console.log(`Sleeping for ${millis} milliseconds`);
  return new Promise((resolve) => {
    setTimeout(() => resolve(), millis);
  });
};

// this could be any heavy I/O e.g.:
// - HTTP requests
// - disk file retrieval
// - TCP / socket calls
const __httpApiCall = (start, end, variable, entityCode, waitBeforeRequest) => {
  // sleep to avoid hitting the API all together
  return sleepPromise(waitBeforeRequest)
    .then(() => {
      // TODO API work to retrieve the data
      const data = [{ start: start, end: end, wait: waitBeforeRequest }];
      console.log(`Done with data: ${JSON.stringify(data)}`);
      return data;
    })
}

const httpApiCall = (inputVar1, inputVar2) => {
  // prepare the array of promises
  let inputSlicesPromises = [[1,2], [3,4], [5,6], [7,8], [9,10]].map((timeSlice) => {
    const currRandomWait = Math.random() * 1000;
    return __httpApiCall(timeSlice[0], timeSlice[1], inputVar1, inputVar2, currRandomWait);
  });
  // perform the HTTP requests
  return Promise.all(inputSlicesPromises)
    .then(slicesLists => {
      // deal with the retrieved data
      return console.log(`slicesLists: \n${JSON.stringify(slicesLists, null, 2)}`);
    })
};


// ---------------------

httpApiCall("foovar", "barvar");

The output is:

Sleeping for 844.8424208593117 milliseconds
Sleeping for 44.40659758801524 milliseconds
Sleeping for 5.6841723462950355 milliseconds
Sleeping for 855.9312108212976 milliseconds
Sleeping for 387.0777718254672 milliseconds
Done with data: [{"start":5,"end":6,"wait":5.6841723462950355}]
Done with data: [{"start":3,"end":4,"wait":44.40659758801524}]
Done with data: [{"start":9,"end":10,"wait":387.0777718254672}]
Done with data: [{"start":1,"end":2,"wait":844.8424208593117}]
Done with data: [{"start":7,"end":8,"wait":855.9312108212976}]
slicesLists: 
[
  [
    {
      "start": 1,
      "end": 2,
      "wait": 844.8424208593117
    }
  ],
  [
    {
      "start": 3,
      "end": 4,
      "wait": 44.40659758801524
    }
  ],
  [
    {
      "start": 5,
      "end": 6,
      "wait": 5.6841723462950355
    }
  ],
  [
    {
      "start": 7,
      "end": 8,
      "wait": 855.9312108212976
    }
  ],
  [
    {
      "start": 9,
      "end": 10,
      "wait": 387.0777718254672
    }
  ]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment