async-waterfall icon indicating copy to clipboard operation
async-waterfall copied to clipboard

Refactoring

Open w-wilbur opened this issue 5 years ago • 0 comments

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)
    }
}

w-wilbur avatar Mar 17 '19 08:03 w-wilbur