async/await
The keywords `async` and `await` let you write code that pauses a function while it waits for a result, such as a server response, without blocking the thread during the wait.
Also known as: асинхронность
What problem does it solve?
A page that requests data from a server still needs to respond to clicks while the request is in flight. With await, you can put the code that uses the response directly below the code that requests it, without nesting callbacks. The waiting function pauses, but the thread is free to run other work. Asynchronous programming is the broader idea; async/await is one way to express it.
What happens when JavaScript hits await?
An async function always returns a promise. Returning a plain value fulfills that promise with the value; an uncaught exception rejects it. The function starts running as soon as you call it, and everything up to its first await runs synchronously.
At await, the function suspends and execution returns to the caller. Once the awaited promise settles, the function's continuation runs as a microtask. This means it cannot resume inline, even if the promise was already fulfilled. A fulfilled promise gives await a value; a rejected one acts like a throw at the await expression, so a surrounding try/catch can handle it.
Example: choosing when to wait
Suppose a product page needs inventory and review data. Both calls take a product ID, but neither needs the other's result:
async function loadProductDetails(id) {
const inventoryRequest = loadInventory(id);
const reviewsRequest = loadReviews(id);
const [inventory, reviews] = await Promise.all([
inventoryRequest,
reviewsRequest,
]);
return { inventory, reviews };
}
The calls start the requests; Promise.all waits for their results. Its result array follows input order, even if the reviews arrive first. If either promise rejects, the combined promise rejects, but that does not cancel the other request. If one call needs data from the other, put an await between the calls: the extra wait reflects a real dependency.
Where it helps—and where it doesn't
Use async/await with asynchronous APIs for network requests, database queries, and file operations. Adding async to a function does not turn blocking I/O into non-blocking I/O or move a CPU-heavy loop to a worker. Also, if you call an async function without awaiting it, returning its promise, or attaching a rejection handler, failures can go unhandled.
Don't assume that every language starts async functions the same way. In Python, for example, calling an async def function creates a coroutine object. Its body does not run until the coroutine is awaited or scheduled.
How it comes up in interviews
For a JavaScript output-order question, trace the synchronous statements first, then identify which lines resume as microtasks. In a code review exercise, explain whether operations depend on each other, whether their waits can overlap, and where a rejection will be handled.