sindresorhus/p-times

Allow the loop to end early?

Open

#1 opened on Oct 28, 2016

View on GitHub
 (4 comments) (1 reaction) (0 assignees)JavaScript (42 stars) (6 forks)user submission
enhancementhelp wanted

Description

Normal for loops can end early by using break or return. Might be useful to have the ability here too. Does that make sense?

Possible implementations:

1

Add a method for ending the iteration in the second argument to mapper: mapper(index, stop):

pTimes(5, (i, stop) => {
    if (shouldStop(i)) {
        stop();
        return;
    }

    return `foo ${i}`;
}).then();

2

Add ability to throw a special error to end the iteration without rejection the promise:

pTimes(5, i => {
    if (shouldStop(i)) {
        throw new pTimes.StopError();
    }

    return `foo ${i}`;
}).then();

3

Add ability to return special Symbol to end the iteration:

pTimes(5, i => {
    if (shouldStop(i)) {
        return pTimes.StopSymbol;
    }

    return `foo ${i}`;
}).then();

While 2 and 3 are more verbose, they have the benefit of working even in a nested promise chain.

Contributor guide