all files / modules/ async.js

98.08% Statements 51/52
94.44% Branches 51/54
100% Functions 10/10
97.06% Lines 33/34
1 statement, 1 function, 6 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 180×   180× 180×   180× 284×   148× 148× 148×         148×   148× 14× 134× 10×           148×           180× 148×   108× 12× 10×   108× 108×       180× 288×   284× 284×       180×    
export default function asyncProcess(functions, { isCancelled, toState, fromState, additionalArgs }, callback) {
    let remainingFunctions = Array.isArray(functions) ? functions : Object.keys(functions);
 
    const isState = obj => typeof obj === 'object' && obj.name !== undefined && obj.params !== undefined && obj.path !== undefined;
    const hasStateChanged = state => state.name !== toState.name || state.params !== toState.params || state.path !== toState.path;
 
    const processFn = (done) => {
        if (!remainingFunctions.length) return true;
 
        const isMapped = typeof remainingFunctions[0] === 'string';
        const errVal = isMapped ? remainingFunctions[0] : {};
        let stepFn  = isMapped ? functions[remainingFunctions[0]] : remainingFunctions[0];
 
        // const len = stepFn.length;
        const res = stepFn.apply(null, additionalArgs.concat([toState, fromState, done]));
 
        Iif (isCancelled()) {
            done(null);
        } else if (typeof res === 'boolean') {
            done(res ? null : errVal);
        } else if (res && typeof res.then === 'function') {
            res.then(
                resVal => {
                    if (resVal instanceof Error) done(resVal, null);
                    else done(null, resVal);
                },
                err => {
                    if (err instanceof Error) console.error(err.stack || err);
                    done(errVal);
                }
            );
        }
        // else: wait for done to be called
 
        return false;
    };
 
    const iterate = (err, val) => {
        if (err) callback(err);
        else {
            if (val && isState(val)) {
                if (hasStateChanged(val)) console.error('[router5][transition] State values changed during transition process and ignored.');
                else toState = val;
            }
            remainingFunctions = remainingFunctions.slice(1);
            next();
        }
    };
 
    const next = () => {
        if (isCancelled()) {
            callback(null);
        } else {
            const finished = processFn(iterate);
            if (finished) callback(null, toState);
        }
    };
 
    next();
}