0
0
Javascriptprogramming~5 mins

Why async and await are needed in Javascript

Choose your learning style9 modes available
Introduction

Async and await help us write code that waits for tasks to finish without stopping everything else. They make working with slow things like loading data easier and cleaner.

When you need to get data from the internet and want to wait for it before continuing.
When you want to read or write files without freezing your program.
When you have tasks that take time and you want your app to stay responsive.
When you want to handle multiple tasks one after another without messy code.
Syntax
Javascript
async function myFunction() {
  const result = await someAsyncTask();
  console.log(result);
}

async marks a function to work with asynchronous code.

await pauses the function until the task finishes, then continues.

Examples
This function returns a promise automatically because it is async.
Javascript
async function greet() {
  return 'Hello!';
}
Here, await waits for the data to load before moving on.
Javascript
async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const json = await response.json();
  console.log(json);
}
Sample Program

This program shows how await pauses the function for 2 seconds without stopping the whole program.

Javascript
async function waitAndSay() {
  console.log('Start');
  await new Promise(resolve => setTimeout(resolve, 2000));
  console.log('Done waiting 2 seconds');
}

waitAndSay();
OutputSuccess
Important Notes

Without async and await, you would use callbacks or .then(), which can be harder to read.

Async functions always return a promise, even if you return a simple value.

Summary

Async and await make waiting for slow tasks easy and clean.

They help keep your program running smoothly without freezing.

Using them makes your code look like normal step-by-step code.