Ad space (banner)
🟨JavaScript Lessons
Lesson 13 / 69

Async Code (Promise / async & await)

In this lesson you'll learn the basics of asynchronous code in JavaScript (Promises and async/await) so you can correctly handle time-consuming operations like network requests. This is for people searching "JavaScript async await usage" or "JavaScript what is a Promise."

When dealing with time-consuming operations (such as network requests), JavaScript uses a mechanism called a Promise. Inside a function marked async, you can use await to "wait" until a Promise's result comes back. It's a mechanism for expressing processing with a time delay, like "waiting for food to arrive after placing an order." If you don't use await, the next line of code runs without waiting for the operation to finish.

The sample code builds a wait function using a Promise that waits for a given amount of time, and inside the main function it waits 300 milliseconds with await wait(300). Run it, and you'll see the second line appear only after a short delay. Notice too that the call to main() is also preceded by await, so the program waits for it to finish before moving on.

A common beginner stumbling block is trying to use await outside of a function, or inside a function that isn't marked async, which causes an error. Remember the rule: await can only be used inside an async function. Another common mistake is trying to use a result before the async operation has finished, resulting in an unexpected undefined.

In real development, all kinds of communication and waiting operations — fetching data from an API, reading a file, running something after a delay — are written using Promises and async/await. When building a web app that involves API communication, this way of thinking about async code is essential foundational knowledge you can't avoid.

When you want to run several async operations at once and wait for all of them to finish, you use Promise.all([task1, task2]). It's faster than awaiting each one in sequence, and it's a common technique when you want to run multiple API requests in parallel.

If an error occurs in an awaited operation, you can catch it with an ordinary try...catch. Being able to handle errors for both async and sync code with the same syntax is one reason async/await is preferred over writing Promises directly.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)