Skip to content

Instantly share code, notes, and snippets.

@BigAB
Last active November 23, 2016 15:48
Show Gist options
  • Save BigAB/297711f37c7d10f5cf907d05e2267261 to your computer and use it in GitHub Desktop.
Save BigAB/297711f37c7d10f5cf907d05e2267261 to your computer and use it in GitHub Desktop.
Async Transform Function in JavaScript
/***************************************************/
function asyncTransform( transforms, val, context ) {
if (typeof val === 'undefined') {
return v => asyncTransform(transforms, v, context);
}
const v = Promise.resolve(val);
if (context) {
transforms = transforms.map( t => v => t.call(context, v));
}
return transforms.reduce((p, t) => p.then(t), v);
}
/***************************************************/
// Use:
const funcs = [
v => v+1,
v => Promise.resolve(v*2), // some sync, some async
v => v*v,
v => Promise.resolve({foo:v})
];
const process = asyncTranform(funcs);
process(1).then( v => console.log(v) ) // { foo: 16 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment