p-map: Allow breaking from iterator

I wish I could stop the iteration early by returning something like pMap.stop (a Symbol) from the iterator.

This is basically the same request as https://github.com/sindresorhus/p-each-series/issues/3

For now, I have to throw an error on purpose just to break it. Thankfully, I don’t need the return value of p-map anyway.

But with this feature, the parts of the array that weren’t computed yet could be set to undefined, or pMap.uncomputed (another Symbol), or even be specified by a valueForUncomputedEarlyStop option.

Can I do a PR?

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Comments: 15 (15 by maintainers)

Most upvoted comments

Ideally, we would also support AbortController, but that can be done later. Just something to keep in mind.

Do we want to call .cancel or similar on all of the incomplete promises if it is stopped?

I agree with your assessment. Let’s go with that. I think we need a better name for that option though.

There are two use-cases I can think of:

  1. Mapping and not caring about the indexes, which means the returned array could be Array#flat()'ed.
  2. Mapping and needing the resulting array to have the same indices, even if incomplete.

So either we can:

  1. Add a pMap option for which behavior to use.
  2. Add two .stop properties where which you choose decides the behavior.
  3. Just return at original indices, and if the user doesn’t care about the indices they can Array#flat() themselves.

Any opinions? What would go with?

Couldn’t we just document that the returned array will be incomplete if the user stops early?

Yes, PR welcome. pMap.stop sounds good.

You can find inspiration for the TS types in https://github.com/sindresorhus/find-up/blob/master/index.d.ts (and testing and docs too, probably)