Skip to content

Promises

When you order food at a restaurant, you do not get your meal the moment you ask. The waiter takes your order and gives you a ticket. The ticket is not food - it is a promise that food is coming. You can hold onto it and wait. When the kitchen is done, the food arrives.

A JavaScript Promise works the same way. It is an object that says "I do not have the result yet, but I will get it to you."


Why promises exist

Some things in JavaScript take time - fetching data from a server, reading a file, waiting for a timer. JavaScript does not stop and wait for those things. It keeps running and comes back when the result is ready.

A Promise is how JavaScript hands you a placeholder while the work happens in the background.


Three states

Every promise is in one of three states:

State Meaning
Pending Work is still happening
Fulfilled Work finished successfully, result is ready
Rejected Something went wrong

A promise starts as pending and moves to either fulfilled or rejected - never back to pending.


Reacting to a promise

You attach callbacks to a promise to say what to do when it settles:

let promise = fetch("/patients")

promise.then(function(result) {
    // runs when fulfilled - result is the value
    console.log(result)
})

promise.catch(function(error) {
    // runs when rejected - error tells you what went wrong
    console.log(error)
})

.then() runs if the promise fulfilled. .catch() runs if it rejected.

You usually chain them rather than storing the promise in a variable:

fetch("/patients")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log("Something went wrong:", error))

fetch() returns a promise

This is the key thing to understand. When you write fetch("/patients"), the browser sends a request to the server. That takes time. So fetch() returns a promise immediately - before the response arrives.

When the response comes back, the promise fulfills and .then() runs with the response.

// fetch() returns a promise right away
let myPromise = fetch("/patients")

// myPromise is pending here - the request is still travelling

myPromise.then(response => {
    // now we have the response - the promise fulfilled
    console.log(response.status)  // 200
})

Challenge

Look at the fetch code you wrote in the Simple APIs group. Find these parts and label them:

  1. Where does fetch() return a promise?
  2. What is the first .then() doing with that promise?
  3. What does the second .then() receive?

Write your answers as comments in the code.


← Arrow Functions    Next: The Fetch Function →