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.
- YouTube 16:9
- Midnight look
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
What Is an Explainer Video?
When words alone make a product, process, or idea hard to explain, an explainer video can show how it works as a narrator describes it.
4 min read Explainer videosHow to Make an Explainer Video, Step by Step
An explainer video uses narration, visuals, or both to explain a product, process, or idea. It can use animation, a screen demonstration, or a person…
4 min read Explainer videosHow to Write an Explainer Video Script
An explainer video helps viewers understand a product, service, process, or idea. Its script covers both the spoken words and what appears on screen,…
4 min read