Asynchronous: Async functions

Async functions are a higher level abstraction over promises.

They are built on promises, so they don’t replace. them, but they expand what promises can do in a really powerful way.

Async functions reduce the boilerplate around promises. They make it so much easier to use them in a more straightforward way.

Suppose you want to use the isFinished promise we defined in the previous lesson.

To use this promise you know you’d have to do something like this:

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

With async functions, you’d write it in this way:

const result = await isFinished
console.log(result)

When the JavaScript engine sees the await keyword, the execution of the current function will halt until the isFinished promise is resolved or rejected.

There’s just one caveat: the enclosing function must be declared as async:

const doSomething = async () => {
  const result = await isFinished
  console.log(result)
}

doSomething()

We can’t call

await isFinished

outside of a function not defined as async.

And remember IIFE, immediately invoked functions? They turn out to be very useful when dealing with async/await, because we can create an IIFE to wrap an async function, and have a more clear syntax compared to defining doSomething and then calling it, like we did above:

(async () => {
  const result = await isFinished
  console.log(result)
})()

Instead of using a .catch() block like in promises, we’d use a try/catch block, for which we’ll learn more about when we’ll talk about errors and exceptions, but here’s a sneak peek:

isFinished.then(ok => {
  console.log(ok)
}).catch(err => {
  console.error(err)
})
try {
  const result = await isFinished
  console.log(result)
} catch(err) {
  console.error(err)
}

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!