top | item 9566041

(no title)

andrus | 10 years ago

I think the confusion stems from the fact that .then() acts like either .map() or .flatMap() depending on the return type.

If .then() was just .flatMap(), you could expect an error if you didn't return a Promise (for example, reject with a TypeError).

If .then() was just .map(), you could return a value of any type (for example, string or Promise<number>) and get back a Promise for a value of that type (Promise<string> or Promise<Promise<number>>).

discuss

order

acjohnson55|10 years ago

Actually, it's slightly more complex because if the result of the function passed to then were somehow a Promise<Promise<something>>, it would be flattened recursively so that the ultimate result is just Promise<something>. (Of course, due to .then's flattening semantics it's highly unlikely you'd have a Promise<Promise<...>> in the first places).

The distinction between map and flatMap makes sense for, say, lists, because you often do want to keep the non-flattened structure around. From promises, I can't think of a reason why that would be desired. You just want to represent the final result after all necessary waiting is completed. I suppose a library could provide stricter map and flatMap for people who deeply care about this.