Last active
November 23, 2016 15:48
-
-
Save BigAB/297711f37c7d10f5cf907d05e2267261 to your computer and use it in GitHub Desktop.
Async Transform Function in JavaScript
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
/***************************************************/ | |
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