Last active
December 8, 2015 15:52
-
-
Save chadxz/b49a3b56af1bda3aa3c2 to your computer and use it in GitHub Desktop.
Serial promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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