Skip to content
tezvyn:

JavaScript Promises: Handling Future Values

Source: developer.mozilla.orgEasyHow cards are made

JavaScript Promises: Handling Future Values

A Promise is an IOU for a future value from an async operation. Instead of blocking your code, you get an object that will eventually contain the result or an error. They're essential for API calls or file reads.

Why it exists

JavaScript is single-threaded, meaning it can only do one thing at a time. If a long-running operation like a network request blocked the main thread, the entire user interface would freeze. Promises were created to manage these asynchronous operations gracefully, allowing other code to run while waiting for the operation to complete.

The mental model

A Promise is a placeholder for a future value. Imagine ordering a coffee: you get a receipt (the Promise) immediately. You can't drink the receipt, but it guarantees you'll eventually get either your coffee (a fulfilled value) or a notice that they're out of beans (a rejected reason). The receipt lets you go sit down and do other things instead of staring at the barista.

How it works

A Promise starts in a pending state. It can transition to one of two settled states. First, fulfilled, meaning the operation succeeded, and the promise now holds a value. Second, rejected, meaning the operation failed, and the promise holds a reason (an error). You attach handlers to a promise using the .then() method for success and the .catch() method for failure. For example, myPromise.then(value => { ... }).catch(error => { ... }). These handlers will execute whenever the promise settles, even if it has already settled before you attach them.

When to use it

Use Promises whenever you perform an operation that doesn't complete instantly. This is standard for all modern web APIs that involve I/O, such as using the fetch() API to get data from a server, reading a file from disk in Node.js, or waiting for a timer to finish. They are the foundation for the more modern async/await syntax, which is just syntactic sugar over Promises.

When not to use it

Do not wrap synchronous code in a Promise. If an operation is instantaneous and doesn't involve waiting (like a simple math calculation or accessing an object's property), creating a promise adds unnecessary complexity. Promises are specifically for managing the delay and outcome of asynchronous actions.

One canonical example

A common use case is fetching data. The fetch function returns a promise that resolves with the server's response.

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch failed:', error));

This code requests data, then uses a .then() block to parse the response as JSON (which is also async), then a second .then() to log the final data, and a .catch() to handle any network or parsing errors.

Interview question

In JavaScript's single-threaded environment, what is the main problem Promises are designed to address?

  • a.To prevent the user interface from freezing during network requests or file I/O.Correct
  • b.To guarantee that all asynchronous operations complete in a specific, predetermined order.
  • c.To enable parallel execution of multiple CPU-bound tasks.
  • d.To automatically retry failed operations without explicit error handling.
Why?

Promises were created to manage asynchronous operations gracefully, allowing other code to run without blocking the main thread, which prevents the user interface from freezing during long-running tasks like network requests. Option C is incorrect because JavaScript remains single-threaded; Promises manage non-blocking I/O, not true parallel CPU execution.

Just read this? Test yourself on what you have been reading.

Read the original → developer.mozilla.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on javascript — each one lists the topics its interview covers.

See open roles