cujojs / when

A solid, fast Promises/A+ and when() implementation, plus other async goodies.
Other
3.44k stars 396 forks source link

Add array based methods to the Promise interface #468

Closed mnahkies closed 1 year ago

mnahkies commented 9 years ago

Propose: Add the array based methods of when to the Promise interface: all, settle, map, filter, reduce, reduceRight, any, and some

Justification: Often the input for these methods will the resolved value of a promise, for example the result of an api request. As these methods are not on the Promise interface, this requires the use of a then that bridges to these methods.

Adding these methods to the Promise interface would result in cleaner code, and avoid an unnecessary intermediate step.

Examples: Map:

when([1, 2, 3, 4])
    .then(inp => when.map(inp))
    .then(console.log); // [1, 4, 9, 16]

when([1, 2, 3, 4])
    .map(x => x * x )
    .then(console.log); // [1, 4, 9, 16]

Filter:

when([1, 2, 3, 4])
    .then(inp => when.filter(inp, x => x % 2))
    .then(console.log); // [1, 3]

when([1, 2, 3, 4])
    .filter(x => x % 2)
    .then(console.log); // [1, 3]

Combined:

whenHaveApiResult()
    .map(MyEntity.fromJSON)
    .filter(myEntity => myEntity.type === 'foobar');

I think that the majority of use cases would be using the map, filter, reduce/reduceRight but that the other methods would be worth including for completeness.

Behaviour when used on a promise that resolves to a single value rather than an array could either copy spreads behaviour and not pass any argument, or convert the value to an array of one.