Skip to content

Instantly share code, notes, and snippets.

@xavierlepretre
Last active May 25, 2019 10:56
Show Gist options
  • Save xavierlepretre/516cf53a8e1fe0ddb85fb94c5ca0d7ad to your computer and use it in GitHub Desktop.
Save xavierlepretre/516cf53a8e1fe0ddb85fb94c5ca0d7ad to your computer and use it in GitHub Desktop.
Like `Promise.all()` but where all promises are started sequentially and it takes an object.
const Promise = require("bluebird");
/**
* @param {!Object.<function.<Promise.<Any>>>} promiseObject. Each key maps to a function
* that returns a promise.
* @returns {!Promise.<Object.<Any>>} The results of the promises passed to the function.
*/
module.exports = function sequentialPromiseNamed(promiseObject) {
const result = Object.keys(promiseObject).reduce(
(reduced, key) => {
return {
chain: reduced.chain
.then(() => promiseObject[ key ]())
.then(result => reduced.results[ key ] = result),
results: reduced.results
};
},
{
chain: Promise.resolve(),
results: {}
});
return result.chain.then(() => result.results);
};
@xavierlepretre
Copy link
Author

xavierlepretre commented Jul 30, 2017

Example:

sequentialPromiseNamed({
        a: () => Promise.resolve(1),
        b: () => Promise.resolve(2)
    })
    .then(console.log);

Prints

{ a: 1, b: 2 }

See full tests: https://github.com/b9lab/promise-extensions/blob/master/test/allSequential.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment