Javascript -async & await

What is async?
async is a keyword used before a function to make it always return a promise.
Example:

async function greet() {
return “Hello!”;
}
greet().then(msg => console.log(msg)); // Output: Hello!

What is await?

await pauses th…


This content originally appeared on DEV Community and was authored by Dharshini E

What is async?
async is a keyword used before a function to make it always return a promise.
Example:


async function greet() {
  return "Hello!";
}
greet().then(msg => console.log(msg)); // Output: Hello!

What is await?

await pauses the execution of an async function until a promise resolves.

Example:


async function fetchData() {
  let promise = new Promise((resolve) => {
    setTimeout(() => resolve("Data received!"), 2000);
  });

  let result = await promise;
  console.log(result); // Output after 2s: Data received!
}
fetchData();

How async and await Work Together

Show how they make asynchronous code** look synchronous.**

Compare code written with .then() vs with async/await.
Error Handling with try...catch

Example:

async function getData() {
  try {
    let res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    let data = await res.json();
    console.log(data);
  } catch (error) {
    console.log("Error:", error);
  }
}
getData();

When to Use async/await

  • When working with API calls (fetch, Axios).
  • When you want cleaner code instead of .then() chains.
  • When error handling is important.


This content originally appeared on DEV Community and was authored by Dharshini E


Print Share Comment Cite Upload Translate Updates
APA

Dharshini E | Sciencx (2025-09-13T01:53:41+00:00) Javascript -async & await. Retrieved from https://www.scien.cx/2025/09/13/javascript-async-await-3/

MLA
" » Javascript -async & await." Dharshini E | Sciencx - Saturday September 13, 2025, https://www.scien.cx/2025/09/13/javascript-async-await-3/
HARVARD
Dharshini E | Sciencx Saturday September 13, 2025 » Javascript -async & await., viewed ,<https://www.scien.cx/2025/09/13/javascript-async-await-3/>
VANCOUVER
Dharshini E | Sciencx - » Javascript -async & await. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/09/13/javascript-async-await-3/
CHICAGO
" » Javascript -async & await." Dharshini E | Sciencx - Accessed . https://www.scien.cx/2025/09/13/javascript-async-await-3/
IEEE
" » Javascript -async & await." Dharshini E | Sciencx [Online]. Available: https://www.scien.cx/2025/09/13/javascript-async-await-3/. [Accessed: ]
rf:citation
» Javascript -async & await | Dharshini E | Sciencx | https://www.scien.cx/2025/09/13/javascript-async-await-3/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.