Skip to content

Instantly share code, notes, and snippets.

@mostr
Last active April 7, 2016 11:01
Show Gist options
  • Save mostr/0b8c9000b67a739b6fc8a3d798d5b8cb to your computer and use it in GitHub Desktop.
Save mostr/0b8c9000b67a739b6fc8a3d798d5b8cb to your computer and use it in GitHub Desktop.
Async functions cannot be used as reducers in sequence
// Lets create some dirs structure (async)
function createDir(name, parent): any {
return new Promise((res, rej) => {
console.log(`Creating ${name} with parent ${parent}`);
res(name);
});
}
const dirsToCreate = ['foo', 'bar', 'baz', 'boo'];
dirsToCreate.reduce(async (parent, dir) => {
console.log(`About to create ${dir} in ${parent}`);
let dirCreated = await createDir(dir, parent);
console.log(`Created ${dirCreated} with parent ${parent}`);
return dirCreated;
}, '/');

The above gives the following result as createDir calls simply "don't wait":

About to create foo in /
Creating foo with parent /
About to create bar in [object Promise]
Creating bar with parent [object Promise]
About to create baz in [object Promise]
Creating baz with parent [object Promise]
About to create boo in [object Promise]
Creating boo with parent [object Promise]
Created foo with parent /
Created bar with parent [object Promise]
Created baz with parent [object Promise]
Created boo with parent [object Promise]

And what I'd like to get is simply:

About to create foo in /
Creating foo with parent /
Created foo with parent /
About to create bar in foo
Creating bar with parent foo
Created bar with parent foo
About to create baz in bar
Creating baz with parent bar
Created baz with parent bar
About to create boo in baz
Creating boo with parent baz
Created boo with parent baz

So, for...of, my friend :)

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