JavaScript Async and Await

JavaScript Tutorial

JavaScript Async and Await

JavaScript Async and Await make asynchronous JavaScript easier to read and write. They are built on top of Promises, but feel more like normal, synchronous code.


Why Async/Await?

Before async/await, we used:

  • Callbacks → callback hell

  • Promises with .then() → better, but still nested sometimes

async/await solves this by making async code look clean and sequential


 The async Keyword

  • Used before a function

  • Always returns a Promise

  • If you return a value, JavaScript automatically wraps it in a Promise


 


 The await Keyword

  • Used inside an async function only

  • Pauses execution until the Promise resolves

  • Makes async code behave like synchronous code


 


How Async/Await Works (Flow)

JavaScript Async and Await
  •  JavaScript waits at await
  •  Other code can run
  •  Execution resumes when Promise resolves

 Async/Await with fetch() (Real Example)


 

  •  No .then() chaining
  •  Clean & readable

 Error Handling with try...catch


 

  •  Errors are handled just like normal JavaScript

 Multiple Await Calls (Sequential vs Parallel)

 Sequential (Slower)

 Parallel (Faster)


 Async Arrow Function


Common Mistakes

  •  Using await outside async
  •  Forgetting try...catch
  •  Assuming await blocks the whole program (it doesn’t!)

Quick Summary

FeatureDescription
asyncMakes a function return a Promise
awaitWaits for a Promise to resolve
try...catchHandles async errors
CleanerReplaces .then() chains

You may also like...