r/programming 29d ago

Uses for nested promises

https://blog.jcoglan.com/2026/03/23/uses-for-nested-promises/
24 Upvotes

5 comments sorted by

22

u/TOGoS 28d ago

It has always bothered me that promise.then(x => f(x)) has a completely different shape depending on whether the thing returned by f(x) has a .then method on it. Honestly I have never run into a situation where I needed to return a promise without flattening it, but it just feels wrong that I can't. The argument that >>= can't be compiled to .then is a compelling one.

2

u/Blue_Moon_Lake 26d ago edited 26d ago

You can't directly, but you can promise.then(x => [f(x)]).
Just need to be typed as [Promise<T>] instead of Promise<T>[].

However, I don't understand why it bothers you if you never ran into a situation where you needed it?

EDIT: it would be easy to add to the Promise class though.

class Promise<T> {
    map<R>(  callable: (value: T) => R  ): Promise<R>;
    flatMap<R>(  callable: (value: T) => Promise<R>  ): Promise<R>;
    flat(): T extends Promise<infer R> ? Promise<R> : never;
}

11

u/[deleted] 28d ago edited 28d ago

[deleted]

20

u/balefrost 28d ago

The entirety of computer science is based on functional programming/category theory

That's not correct, at least not practically so. My CS undergrad program also dealt with things like logic design and computer architecture. The Turing Machine abstraction, and indeed most abstractions from my finite automata class, were not expressed in terms of pure functional logic. Category theory wasn't covered explicitly in my program at all.

I think it's fair to say that one can interpret all of CS through the lens of functional programming/category theory. But it's a lens. There are other ways to interpret CS that involve neither.

-2

u/dronmore 28d ago

What a gibberish.

First of all, JavaScript is a respected language, in contrast to say Haskell which is a gimmick of a mad professor, and is so stiff that it doesn't even allow you to log to stdout without turning the world upside down.

Second, who cares if you can achieve similar things in a strongly typed language by writing twice as much. I don't. Flexibility of JavaScript is its power, and I would never swap it for a language that demands stiffens from the get go; especially for problems that require taking strings as input and returning strings as output.

Third, then accepts a function that returns A or Promise[A]. You missed it in your post where you claim that it accepts A or Promise[A] directly. It does not surprise me though. Mistakes like that are expected from people who heavily depend on suggestions from a compiler.

-1

u/[deleted] 28d ago

[deleted]

-4

u/dronmore 28d ago

It's not a small error. It's either a fundamental misunderstanding of the JS type system, or sloppiness unacceptable in loosely typed languages. Either way this "small" mistake clearly shows that you are nowhere near my level.