Last active
July 9, 2019 13:08
-
-
Save guangtuan/b63bfafcc3b9e874dd7501d7e49ec7e4 to your computer and use it in GitHub Desktop.
compose-async
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 isAsync(fn) { | |
return fn.constructor.name === 'AsyncFunction'; | |
} | |
const compose = (...fns) => { | |
let containsAsync = false; | |
return function (param) { | |
let result = param; | |
while (fns.length) { | |
let currentFn = fns.shift(); | |
if (containsAsync) { | |
result = result.then(currentFn); | |
} else { | |
if (isAsync(currentFn)) { | |
containsAsync = true; | |
result = Promise.resolve(currentFn(result)); | |
} else { | |
result = currentFn(result); | |
} | |
} | |
} | |
return result; | |
} | |
} | |
const func1 = string => string.toUpperCase(); | |
const func2 = async param => { | |
return param.substring(1, 3); | |
}; | |
const func3 = string => { | |
const first = string[0]; | |
return [first, first, first].join(""); | |
}; | |
const exe = compose(func1, func2, func3); | |
(async () => { | |
try { | |
const result = await exe("hello"); | |
console.log(result); | |
} catch (error) { | |
console.log(error); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment