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

Allow the loop to end early? #1

Open
sindresorhus opened this issue Oct 28, 2016 · 4 comments
Open

Allow the loop to end early? #1

sindresorhus opened this issue Oct 28, 2016 · 4 comments

Comments

@sindresorhus
Copy link
Owner

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.

@fregante
Copy link

fregante commented Oct 31, 2016

return pTimes.StopSymbol;

is not substantially more verbose than:

(i, stop) => {
        stop();
        return;

Plus it has the advantage of being global so you don't have to pass a stop function around.

Alternatively:

return pTimes['⛔️']; // 😜

@sindresorhus
Copy link
Owner Author

Thanks for the feedback. I'll go with returning a Symbol and pTimes.end as the name.

Pull request welcome from anyone :)

@Richienb
Copy link
Contributor

Richienb commented Jun 2, 2021

Because this module wraps p-map, this issue should be moved there.

@sindresorhus
Copy link
Owner Author

Yeah, we need to resolve sindresorhus/p-map#31 first.

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

3 participants