Concurrency
Asynchronous Programming
Computer Science
Software Development
JavaScript

Futures vs. Promises

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

markdown
1In the field of software development, particularly in asynchronous programming, "Futures" and "Promises" are important concepts. They assist in managing and controlling the execution of code that can run concurrently. Both are used to represent a value that may not yet be available, due to ongoing computation or uncertainty in retrieving the value. Understanding the differences and nuances between Futures and Promises can greatly enhance your ability to write efficient asynchronous code.
2
3## Technical Explanation
4
5### Futures
6
7A `Future` is a placeholder for a value that will be available at some point in the future. It is essentially a read-only, placeholder object that can be passed around without any knowledge of its state. The future is usually created by the system or a library function and provides a way to retrieve a result once it is available.
8
9#### Example of Future in Python
10
11```python
12import concurrent.futures
13
14def square(x):
15    return x * x
16
17with concurrent.futures.ThreadPoolExecutor() as executor:
18    future = executor.submit(square, 10)
19    print(future.result())  # Output: 100

Promises

A Promise, on the other hand, is a mechanism to write asynchronous code in a more synchronous fashion. A Promise embodies both the task itself and a way to control its execution, meaning you both initiate the computation and retrieve the eventual result in the same object. Formerly, Promises existed primarily in web development but have since evolved to other languages and libraries.

Example of Promise in JavaScript

javascript
1let promise = new Promise((resolve, reject) => {
2    let success = true;
3    setTimeout(() => {
4        if(success) {
5            resolve("Promise resolved");
6        } else {
7            reject("Promise rejected");
8        }
9    }, 1000);
10});
11
12promise.then(result => {
13    console.log(result);  // Output after 1 second: Promise resolved
14}).catch(error => {
15    console.error(error);
16});

Key Differences

markdown
1| Aspect | Future | Promise |
2| ------------ | --------------------------------------------------------- | ----------------------------------------------------- |
3| Initiation | Created usually by a library or a system call | Created by the developer and contains execution logic |
4| State | Read-only, cannot be resolved or rejected by the client | Mutable, can be resolved or rejected by the client |
5| Usage | Typically for retrieving values after computation | Chaining and controlling complex async operations |
6| Language | Found in languages like Java, Python, Scala | Found in JavaScript, modern C++ | ``` |
7
8## Technical Comparison and Use Cases
9
10### Concurrency and Synchronization
11
12* **Futures** are frequently used in pattern designs that necessitate immediate return from a method call while delegating the actual processing to another thread or system. This allows them to make efficient use of systems with multiple cores.
13* **Promises** are better suited for situations where you need to handle a chain of dependent computations, as they inherently manage fulfillment and reject states, enabling more complex coordination of asynchronous operations via chaining.
14
15### When to Use Futures vs. Promises
16
17* **Futures**: Prefer using futures when your application deals with simple retrieval of data or results after some asynchronous operation is complete. Deployment typically leans on APIs designed for futures, like those in Java's `CompletableFuture` or Python's `concurrent.futures`.
18* **Promises**: Use promises when your application involves complex task orchestration or error handling within asynchronous operations. It's a prime choice for user-interface related asynchronous tasks in web development (JavaScript promises being a prominent example).
19
20## Conclusion
21
22The choice between Futures and Promises often comes down to the particular requirements of the system being designed and the strengths of the underlying programming language being used. Futures are ideal for simple, one-time event results, while Promises offer the flexibility needed for complex asynchronous task management. Both are foundational to modern computing systems, enabling developers to write non-blocking code for applications that remain responsive and efficient.
23
 

Course illustration
Course illustration

All Rights Reserved.