Facebook Pixel

How async/await Works Behind the Scenes in JavaScript

async/await is syntactic sugar over promises. Here is what the engine does under the hood.

How async/await Works Behind the Scenes in JavaScript

async/await is syntactic sugar over promises. Understanding what happens behind the scenes helps you reason about timing and errors.

async Functions Return Promises

async function foo() { return 42; } // is roughly equivalent to: function foo() { return Promise.resolve(42); }

If you return a value, it is wrapped in Promise.resolve. If you throw, it is wrapped in Promise.reject.

await Yields to the Event Loop

When await is hit, the async function pauses and returns a pending promise to the caller. Control goes back to the caller.

async function foo() { console.log("1"); await Promise.resolve(); console.log("2"); } foo(); console.log("3"); // output: 1, 3, 2
  1. foo() is called. "1" logs.
  2. await pauses foo. The rest ("2") is scheduled as a microtask.
  3. "3" logs (synchronous, on the stack).
  4. Stack is empty. Microtasks run: "2" logs.

await Unwraps the Promise

await promise returns the fulfilled value. If the promise rejects, await throws the rejection reason.

The Rest of the Function Is a Microtask

After await, the rest of the async function runs as a microtask (when the awaited promise settles). This is why async functions do not block the main thread.

The Takeaway

async functions return promises. await pauses the function and yields control to the caller. The rest of the function runs as a microtask when the awaited promise settles. await unwraps the promise (fulfilled value) or throws (rejection). This is why async functions do not block.

async functions return promises. await pauses the function and yields control to the caller. The rest of the function runs as a microtask when the awaited promise settles. await unwraps the promise or throws the rejection reason.

No. await pauses the async function and yields control to the caller. The caller continues running synchronous code. The rest of the async function runs as a microtask when the awaited promise settles.

Code before await runs synchronously. await pauses and schedules the rest as a microtask. Code after the foo() call runs next (sync). Then the rest of foo runs (microtask). So: 1, 3, 2.

Yes. async functions return promises. await unwraps promises. try/catch with await is equivalent to .catch with .then. You can mix await with Promise.all.

As a microtask, when the awaited promise settles. The event loop runs microtasks after the current synchronous code completes and before the next macrotask. This is why async functions do not block.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.