Skip to content

Instantly share code, notes, and snippets.

@tjunghans
Last active May 16, 2017 12:12
Show Gist options
  • Save tjunghans/fd0a45ae6d8c79020f0647bd7c051e8a to your computer and use it in GitHub Desktop.
Save tjunghans/fd0a45ae6d8c79020f0647bd7c051e8a to your computer and use it in GitHub Desktop.
Promises in sequence

Promises in Sequence

If you have multiple promises, an array of promises, and you want to perform an action after they all have resolved you can use Promise.resolve(). However if you'd like the same result, whilst having the promises called in order you will need to come up with a custom solution because there is no api for that.

Let's create a promise factory to generate our promises that we want to execute in sequence:

function createP(id) {
  return new Promise((resolve, reject) => {
    console.log(id);
    const timeout = Math.random() * 100;
    setTimeout(() => {
      resolve({ id, timeout });
    }, timeout);
  });
} 

The inSequence function which takes an array of promises as an argument:

function inSequence(promises) {
  return promises.reduce((prev, next) => {
    return prev.then((prevRes => {
        return next.then(nextRes => {
            prevRes.push(nextRes); // take the previous result and append the next to it
            return prevRes;
        });
    }));
  }, Promise.resolve([]));
}

Usage:

const promises = [
  createP(7), createP(5), createP(3)
];
inSequence(promises).then(res => {
    console.log(res);
});

Result:

[
  {
    "id": 7,
    "timeout": 56.985111228065755
  },
  {
    "id": 5,
    "timeout": 25.835860521855423
  },
  {
    "id": 3,
    "timeout": 13.25073904955656
  }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment