[JS] JavaScript Parallel Promise Tutorial

For those who haven’t heard of Promise in JavaScript before, it is a function to make JavaScript wait for something before running other operation. It is implemented in modern browsers, or just use one of those Promise polyfill.

Promise can wait for one or more operations to be done. Obvious use cases would be to get all the data from various sources before rendering dashboard.

If you are looking for a way to use Promise to wait for 1 operation only, article on PromiseJS website would be good enough.

Promise.all for parallel operations

However, today I was looking for a way to wait for many operations at the same time. It took me 2 hours to assemble piece of knowledge from PromiseJS website, Mozilla Developers, and our friend Stackoverflow.

Here is step by step guide to implement Promise:

1) Download Promise polyfill and add it to your project. I am using this one: Promise polyfill

2) Use the code below, feel free to adapt to your required task:

function loadFile(filename) {
  return new Promise(function(resolve, reject) {
      // do anything blah blah blah
      // when done
      // or use: resolve(value) if you want to return something

Promise.all([loadFile(file1), loadFile(file2)]).then(function(results) {
   // Something to do when they are all done !

Note that since Promise.all get argument as Array, we can also create new Array and push the promise function as many as we want before using it in Promise.all.

3) There is no step 3. Enjoy the promise !







One response to “[JS] JavaScript Parallel Promise Tutorial”

  1. آموزش javascript Avatar
    آموزش javascript

    Thanks for sharing nice tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *