5.7 Sequential execution

Promise chains contain promises which are executed in a sequential way. This means that a promise in the chain is not executed until the preceding promise in the chain has been fulfilled. We can use loops or a recursive function to run some promises in a sequential way. This is useful when dealing with a promise chain with dynamic length.

Getting Ready

All you need to implement this recipe is an installation of TypeScript 2.0 or higher and jQuery.

How to do it

We are going to write a promise to load some files via AJAX:

  const files = [
    '/data/countries.json',
    '/data/user_profile.json'
  ];

  function loadFile(file) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: file,
        async: true,
        method: 'GET',
        dataType: 'json',
        success: function (data) {
          resolve(data);
        },
        error: function (e) {
          reject(e);
        }
      });
    });
  }

We are going to also declare a helper function to execute a promise for each file to be loaded:

  function runSequence(array, callback) {
    return new Promise((resolve, reject) => {
      const results = [];

      function chain(array, index) {
        if (index === array.length) return resolve(results);
        Promise.resolve(callback(array[index]))
          .then((content) => {
            results.push({success: true, result: content});
            chain(array, index + 1);
          })
          .catch((e) => {
            results.push({success: false, result: e});
            chain(array, index + 1);
          });
      }
      chain(array, 0);
    });
  }

We are now ready to load our files in using sequential execution:

runSequence(files, loadFile).then((contents) => {
  console.log(contents);
});

How it works

The number of files to be loaded is configurable and each file is loaded using a promise. Because the number of files is configurable we are dealing with a promise chain with dynamic length. If the files can be loaded in parallel we should try to run the promises using parallel execution but let’s imagine that the files must be loaded in a particular order for the sake of this example. The sequential execution of the promises is achieved thanks to the usage of a recursive function named chain which iterates through all the promises in the chain.

Source Code

Sequential execution

See also

Please refer to the other recipes about promises in this chapter to learn about more bluebird and the promises API.


Shiv Kushwaha

Author/Programmer