Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise.serial() method #6

Open
rogierschouten opened this issue Jul 3, 2015 · 0 comments
Open

Promise.serial() method #6

rogierschouten opened this issue Jul 3, 2015 · 0 comments

Comments

@rogierschouten
Copy link

Maybe add a library of these functions applicable to any ES6 promise, instead of putting them on Promise, but...

/**
 * Executes the callback for each value serially: the next callback starts once the previous has finished.
 * If any callback returns an error, the process is stopped and the error returned.
 */
export function tsSerial<T>(values: T[], callback: (value: T) => tsPromise.Promise<void>): tsPromise.Promise<void> {
    if (values.length === 0) {
        return tsPromise.Promise.resolve();
    }

    var i = 0;

    function doTail(): tsPromise.Promise<void> {
        var p = callback(values[i]);
        i++;
        if (i >= values.length) {
            return p;
        } else {
            return p.then((): tsPromise.Promise<void> => doTail());
        }
    }

    return doTail();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants