Asynchronous: Promises

Promises are another way to handle asynchronous code.

Here’s a simple example of a promise:

let done = true

const isFinished = new Promise((resolve, reject) => {
  if (done) {
    const workDone = 'Here is the thing I built'
    resolve(workDone)
  } else {
    const why = 'Still working on something else'
    reject(why)
  }
})

You create a promise using the new Promise() syntax, which accepts a function.

That function gets two parameters, resolve and reject:

new Promise((resolve, reject) => {

})

Inside the function you do some work, and then you either call resolve() or reject(), because those 2 parameters are functions.

By the name of those 2 functions, you can imagine the consequences.

The promise is either fulfilled, or rejected.

In the above example, we call resolve() when done is true. You can change done to false, and the promise will fail.

What does it mean? It means that when we’ll use the promise, we’ll be able to handle a different scenario.

Here’s how to use a promise:

isFinished.then(ok => {
  console.log(ok)
}).catch(err => {
  console.error(err)
})

This code will execute the isFinished() promise and will wait for it to resolve.

When this happens, the code inside the then() function callback will be executed.

If there is an error and the promise is rejected, we will handle it in the catch callback.

Lessons in this unit:

0: Introduction
1: Callbacks
2: Timers
3: ▶︎ Promises
4: Async functions
5: Chaining promises
6: Orchestrating promises
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!