pls expalin me Async await JavaScript
Loading
pls expalin me Async await JavaScript
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Abhishek YadavRank #217 · 11.3K reputationPosted Mar 14, 2024, 1:43 AM EDT
async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } fetchData();Async await is a feature in JavaScript that allows you to work with asynchronous code in a more synchronous way. When you mark a function with the
asynckeyword, it automatically returns a Promise. Inside an async function, you can use theawaitkeyword to wait for a Promise to resolve before continuing with the code execution.Here's an example of how async await can be used:
Naimish MakwanaRank #324 · 7.7K reputationPosted Mar 15, 2024, 1:04 AM EDT
The
asyncandawaitkeywords are special syntax in JavaScript that are used to work with promises in a more comfortable and readable way.Async Function: An
asyncfunction is a function that implicitly returns a promise. Theasynckeyword before a function means that the function will always return a promise. Any value returned by the function is wrapped in a resolved promise automatically. Here’s an example:async function f() { return 1; } f().then(alert); // 1In the above example, the function
f()returns a resolved promise with the result of1.Await Keyword: The
awaitkeyword is used inside anasyncfunction to pause its execution and wait for a promise to resolve or reject before continuing. Here’s an example:async function f() { let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("done!"), 1000) }); let result = await promise; // wait until the promise resolves alert(result); // "done!" } f();In the above example, the function execution pauses at
let result = await promise;and resumes when the promise settles, withresultbecoming its result. So, the code shows “done!” after one second12.Remember, the
awaitkeyword can only be used inside anasyncfunction3. If we try to useawaitin a non-async function, there would be a syntax error1.This
async/awaitsyntax provides a way of maintaining cleaner and more readable code when working with asynchronous operations12.Thanks
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 14, 2024, 4:18 PM EDT
awaitkeyword can only be used inside an async function.awaitkeyword then returns the resolved value of the Promise.// Asynchronous function declared with async keyword async function asyncFunction() { // Create a Promise that resolves after 2 seconds const delayPromise = new Promise(resolve => { setTimeout(() => { resolve('Resolved after 2 seconds'); }, 2000); }); // Pause execution of the function until the delayPromise settles const result = await delayPromise; // This line will be executed after the delayPromise settles console.log(result); // Output: Resolved after 2 seconds } // Calling the async function asyncFunction();Tuhin PaulRank #7 · 71.9K reputationPosted Mar 14, 2024, 4:15 PM EDT
// Function that returns a Promise resolving after a specified time function delay(ms) { return new Promise(resolve => { setTimeout(() => { resolve(`Promise resolved after ${ms} milliseconds`); }, ms); }); } // Using Promise with then/catch delay(2000) .then(message => { console.log(message); // This will be executed when the Promise is resolved }) .catch(error => { console.error(error); // This will be executed if the Promise is rejected }); // Using async/await async function runAsync() { try { const message = await delay(3000); // Wait for the Promise to be resolved console.log(message); // This will be executed when the Promise is resolved } catch (error) { console.error(error); // This will be executed if the Promise is rejected } } runAsync();Tuhin PaulRank #7 · 71.9K reputationPosted Mar 14, 2024, 4:16 PM EDT
// Asynchronous function declared with async keyword async function asyncFunction() { return 'Hello from async function'; } // Calling the async function const resultPromise = asyncFunction(); // Handling the Promise returned by the async function resultPromise.then(result => { console.log(result); // Output: Hello from async function });asynckeyword is used to declare asynchronous functions.Vishal YelveRank #178 · 13.6K reputationPosted Mar 15, 2024, 4:47 AM EDT
Hi Gomij,
Do refer below links, which will help u to understand with examples
https://www.freecodecamp.org/news/javascript-async-await/
Md SarfarajRank #194 · 12.4K reputationPosted Mar 17, 2024, 10:29 AM EDT
Please check out the video below. He explained everything very well.
Link: https://www.youtube.com/watch?v=8aGhZQkoFbQ