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.
Promises
In theory promises are straightforward. In practice promises are challenging to understand when creating complex dependencies. Let's break down the core dependencies.
Promise Resolution
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.
Promise Chaining
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
Putting All Together
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.
Conclusion
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