RSS Amplifier

The Weekend Read · Nov 24, 2024

Issue 46 - The Logic of Promises

0
Sign in to vote or save

Dominik Tornow · The Weekend Read

Another weekend, another weekend read, this time all about the Logic of Promises.

Promises are a fundamental abstraction for coordinating concurrent processes: A promise represents a synchronization barrier between two processes, enabling one process to await the completion of another process.

In theory promises are straightforward. In practice promises are challenging to understand when creating complex dependencies. Let's break down the core dependencies.

A promise is instantiated with an executor, a function that returns a value or returns a promise. If the executor returns:

  • a value, the promise resolves with that value

  • a promise, the outer promise resolves with the value of the inner promise

Importantly, although the executor may return another promise, that promise is not externalized, it stays internal.

\(\underbrace{Promise(() => \underbrace{Promise(() => \underbrace{Promise(() => 42)))}_\text{Promise Inner 2}}_\text{Promise Inner 1}}_\text{Promise Outer} = 42 \)

Another mechanism is promise chaining. A promise defines a .then method that accepts a continuation, a function that similar to an executor returns a value or a promise.

Importantly, .then returns a new promise that is externalized

\(\underbrace{Promise(() => 21)}_\text{Promise P1}.\underbrace{then((v) => v + 21)}_\text{Promise P2} = 42\)

Promise resolution and promise chaining enable complex coordination, with the former enabling the completion of tasks depending on other tasks and the later enabling the construction new tasks depending on other tasks.

Crucially, in the case of promise resolution, the origin promise resolves last, whereas in the case of promise chaining, the origin promise resolves first.

Promises may seem simple at first glance, but their true power lies in their ability to orchestrate complex flows with two simple mechanics.

Happy Reading

Read the original on dtornow225.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.