Programming
Futures and Promises
Asynchronous Programming
Software Development
Coding Concepts

What's the difference between a Future and a Promise?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When discussing asynchronous programming in many modern programming languages, two predominant concepts often arise: Futures and Promises. These concepts facilitate handling operations that might not yield results immediately, such as downloading a file, querying a database, or calling a web service. Despite their similarities, Futures and Promises have distinct roles and functionalities in managing asynchronous tasks.

Understanding Futures and Promises

Future

A Future is an object representing the eventual completion or failure of an asynchronous operation. Essentially, it acts as a read-only placeholder for a value that may not yet exist. Most implementations of Futures provide methods to check if the future has been completed (isDone), to await and retrieve the result (get), and to register callbacks to be executed upon completion. However, you cannot manually complete or resolve a Future directly with a value; it is controlled by the operation that returns it.

Languages like Java and Scala use Futures extensively. For example, in Java, the java.util.concurrent.Future interface represents a Future, and you typically retrieve its result using the get() method, which blocks until the result is available.

Promise

A Promise, on the other hand, can be thought of as the writable counterpart to a Future. It is an object representing the eventual completion or failure of an asynchronous operation, but unlike a Future, you can resolve or reject a Promise manually. This feature makes Promises ideal for scenarios where you need explicit control over the asynchronous operation's resolution. Often, a Promise will generate a Future, which can be handed out to other parts of the program to read the eventual result.

Languages like JavaScript utilize Promises extensively. Here, you create a Promise with two functions: resolve and reject, which control the state of the Promise. For instance:

javascript
1let myPromise = new Promise((resolve, reject) => {
2    setTimeout(() => {
3        resolve("Operation succeeded");
4    }, 1000);
5});
6
7myPromise.then(value => console.log(value));

In this example, the Promise resolves with a string after a delay, and its success message is logged to the console via a callback supplied to then.

Key Differences

To encapsulate the main differences, we can summarize as shown in the table:

FeatureFuturePromise
ControlRead-onlyWritable (can be manually resolved/rejected)
UsageConsuming the result of an async operationProducing the result of an async operation
Typical FunctionsisDone, get, get(timeout, unit)resolve, reject, then, catch
Common inJava, ScalaJavaScript, Python (as asyncio.Future)

Practical Implications

Use in Multithreading

Futures are often used in environments that utilize multithreading, like in Java with ExecutorService which returns a Future object when you submit a Callable task. This pattern allows other threads to continue working without blocking, waiting for the Future to complete to process its result.

Event-Driven Programming

Promises are particularly useful in event-driven environments such as Node.js, where non-blocking operations are fundamental. Here, Promises simplify handling asynchronous operation chains — significantly managing the "callback hell" scenario, where callbacks are nested within callbacks, leading to complex and hard-to-maintain code.

Conclusion

Both Futures and Promises are integral to writing effective and efficient asynchronous code. The choice between using a Future or a Promise usually depends on the specific requirements of the application, such as the environment (server side vs. client-side) or the particular language's capabilities and idiomatic usage. By understanding the distinctions and appropriate applications of each, developers can better manage asynchronous operations in their applications.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.