Skip to content
explainroo

JavaScript: callbacks to async/await

How JavaScript code goes from nested callbacks to promises to async and await, with one small example that changes step by step.

Transcript

How does JavaScript handle two requests that depend on each other? Our helper functions fetch a user, then that user’s orders, and display them.

Here, a callback is a function that runs after a result arrives. When the user arrives, its callback starts fetching orders. Another callback displays them.

Now use helpers that return promises, which represent future results. A then handler receives the user, and returns the promise for their orders.

Returning that promise makes the next handler wait for the orders. A catch handler handles failures from either request.

The async keyword lets a function use await expressions. Each await gives us the result when its promise succeeds.

While this function is waiting, other JavaScript can keep running. A rejected promise makes this function throw, so try and catch handle failures.

Callbacks nest the steps, and promises connect them through handlers. The async and await keywords make promise based code easier to read.

More from technology

Related guides