-
-
Save tingwei628/4b8adeff9049d23e09d9b12c384e453a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 sequentialCallback (...fns) { | |
return (...args) => { | |
const done = args.pop() | |
const next = (error, ...args) => { | |
if (error) return done(error) | |
if (fns.length) { | |
const fn = fns.shift() | |
return fn(...args, next) | |
} | |
return done(null, ...args) | |
} | |
return next(null, ...args) | |
} | |
} |
Author
tingwei628
commented
Nov 20, 2016
Another form
var _slice = [].slice
function sequentialCallback () {
var fns = _slice.call(arguments)
return function () {
var args = _slice.call(arguments)
var done = args.pop()
var next = function () {
var args = _slice.call(arguments)
var error = args.shift()
if (error) return done(error)
if (fns.length) {
var fn = fns.shift()
return fn.apply(null, args.concat([next]))
}
return done.apply(null, [null].concat(args))
}
return next.apply(null, [null].concat(args))
}
}
Compared to the form with Promise
findSomething()
.then(transformSomething)
.then(validateTransformed)
.then((validated) => console.log('data is valid:', validated))
.catch((error) => console.error(new Error(error))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment