async-waterfall
async-waterfall copied to clipboard
Refactoring
Hi, I tried to re-implement this functionality with the following code. Please correct me if there is any mistake.
function waterfall(fns, cb) {
if (Reflect.toString.call(fns) !== '[object Array]') {
throw Error('waterfall第一个参数必须为数组')
}
if (typeof cb !== 'function') {
throw Error('waterfall第二个参数必须为函数')
}
let [fnErr, fnArgs, isBreak] = [null, [], false]
const fnCb = function (err, ...args) {
fnErr = err
fnArgs = args
}
for (const fn of fns) {
if (fnErr !== null) {
isBreak = true
cb(fnErr)
break
}
fn(...fnArgs, fnCb)
}
if (!isBreak) {
cb(fnErr, ...fnArgs)
}
}