import tryFn from './tryFn';
import WaterfallError from './waterfallError';

export default function waterfall(tasks, ...args) {
    let
        results = [];

    return tasks.reduce(
        (promise, task) => promise.then((promiseResults) => {
            return tryFn(task, ...promiseResults)
                .then((taskResults) => {
                    return results = Array.isArray(taskResults)
                        ? taskResults
                        : [taskResults];
                });
        }),
        Promise.resolve(args)
    )
        .catch((error) => {
            let waterfallError = new WaterfallError();
            waterfallError.message = error.message;
            waterfallError.results = results;
            throw waterfallError;
        });
};
import tryFn from './tryFn';
import WaterfallError from './waterfallError';

export default function waterfall(tasks, ...args) {
    if (!Array.isArray(tasks)) {
        return Promise.reject(new Error('First argument to waterfall must be an array of functions'))
    }

    let
        results = [];

    return tasks.reduce(
        (promise, task, index) => promise.then((promiseResults) => {
            return tryFn(task, ...promiseResults)
                .then((taskResults) => {
                    if (index == tasks.length - 1) {
                        return taskResults;
                    } else {
                        return results = Array.isArray(taskResults)
                            ? taskResults
                            : [taskResults];
                    }
                });
        }),
        Promise.resolve(args)
    )
        .catch((error) => {
            let waterfallError = new WaterfallError();
            waterfallError.message = error.message;
            waterfallError.results = results;
            throw waterfallError;
        });
};

Update waterfall to return the last task results unchanged.