0
0
Javascriptprogramming~5 mins

Await keyword behavior in Javascript

Choose your learning style9 modes available
Introduction

The await keyword pauses your code until a task finishes, making it easier to work with things that take time, like loading data.

When you want to wait for data from the internet before continuing.
When you need to pause your code until a file finishes loading.
When you want to make sure one step finishes before starting the next.
When you want to write simpler code that looks like normal steps but handles waiting.
When you want to avoid confusing chains of commands and make your code easier to read.
Syntax
Javascript
let result = await someAsyncFunction();

await can only be used inside async functions.

It waits for a Promise to finish and gives you the final value.

Examples
Waits for the fetch to finish, then parses and prints the data.
Javascript
async function getData() {
  let response = await fetch('https://api.example.com/data');
  let data = await response.json();
  console.log(data);
}
Waits one second before printing a message.
Javascript
async function waitAndPrint() {
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('One second passed');
}
Awaits a Promise that immediately resolves with 42.
Javascript
async function example() {
  let value = await Promise.resolve(42);
  console.log(value); // prints 42
}
Sample Program

This program waits half a second to get a number, then prints it. The await pauses the code until the number is ready.

Javascript
async function fetchNumber() {
  // Simulate a delayed number fetch
  return new Promise(resolve => setTimeout(() => resolve(7), 500));
}

async function main() {
  console.log('Start fetching...');
  let number = await fetchNumber();
  console.log('Number received:', number);
  console.log('Done');
}

main();
OutputSuccess
Important Notes

If you forget to use async before a function, await will cause an error.

await makes your code wait without freezing the whole program.

You can use await with any Promise, not just fetch or timers.

Summary

await pauses code until a Promise finishes.

It must be inside an async function.

Using await makes asynchronous code easier to read and write.