0
0
Javascriptprogramming~5 mins

Async function syntax in Javascript

Choose your learning style9 modes available
Introduction

Async functions let your code wait for things like data from the internet without stopping everything else. This makes your programs faster and smoother.

When you need to get data from a website or server.
When you want to wait for a timer or delay without freezing the page.
When you want to handle tasks that take time, like reading files or databases.
When you want your program to keep working while waiting for something to finish.
Syntax
Javascript
async function functionName(parameters) {
  // code that can use await
}
Use the async keyword before function to make it asynchronous.
Inside an async function, you can use await to pause until a promise finishes.
Examples
A simple async function that returns a greeting.
Javascript
async function greet() {
  return 'Hello!';
}
This function waits 1 second before printing a message.
Javascript
async function waitAndSay() {
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('One second passed');
}
An async arrow function that fetches data from a website and returns it as JSON.
Javascript
const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
};
Sample Program

This program waits 1.5 seconds and then prints a message. It shows how async and await work together to pause and resume code.

Javascript
async function fetchMessage() {
  // Simulate waiting for data
  const message = await new Promise(resolve => {
    setTimeout(() => resolve('Data received!'), 1500);
  });
  console.log(message);
}

fetchMessage();
OutputSuccess
Important Notes

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

Use await only inside async functions to pause until a promise resolves.

Async functions help keep your app responsive by not blocking other code while waiting.

Summary

Async functions let you write code that waits for things without stopping everything else.

Use async before a function and await inside it to pause for promises.

This makes handling slow tasks like fetching data easier and cleaner.