Skip to content

Instantly share code, notes, and snippets.

@chadxz
Last active December 8, 2015 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadxz/b49a3b56af1bda3aa3c2 to your computer and use it in GitHub Desktop.
Save chadxz/b49a3b56af1bda3aa3c2 to your computer and use it in GitHub Desktop.
Serial promises
const keyedObj = {
foo: 'fooVal',
bar: 'barVal',
baz: 'bazVal'
};
function concatAsync(acc, val) {
console.log(`processing '${val}'`);
return new Promise(resolve => {
resolve(acc.concat(val));
});
}
function concatKeysAsync(obj) {
let p = Promise.resolve([]);
Object.keys(obj).forEach(k => {
p = p.then(res => {
return concatAsync(res, k);
});
});
return p;
}
concatKeysAsync(keyedObj).then(res => {
console.log('all done', res);
});
/*
$ babel-node serialPromises.js
processing 'foo'
processing 'bar'
processing 'baz'
all done [ 'foo', 'bar', 'baz' ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment