Skip to content

Commit 05b3896

Browse files
committed
async await javascript
1 parent 4f5454a commit 05b3896

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//Async await
2+
//Async await is a syntactic sugar over promises, making asynchronous code look
3+
// and behave more like synchronous code. It is built on top of promises
4+
// and allows you to write cleaner and more readable code when dealing with asynchronous operations.
5+
6+
// An async function is a function that is declared with the async keyword,
7+
// and it always returns a Promise. The await keyword can only be used inside async functions.
8+
// When you use await, it pauses the execution of the async function until the Promise is resolved or rejected.
9+
// Creating an async function
10+
async function fetchData() {
11+
try {
12+
// Simulating an asynchronous operation using a Promise
13+
const data = await new Promise((resolve, reject) => {
14+
setTimeout(() => {
15+
const success = true; // Change this to false to simulate a failure
16+
if (success) {
17+
resolve("Data fetched successfully!");
18+
} else {
19+
reject("Failed to fetch data.");
20+
}
21+
}, 2000); // 2 seconds delay
22+
});
23+
console.log("Success:", data); // This will run if the promise is fulfilled
24+
} catch (error) {
25+
console.error("Error:", error); // This will run if the promise is rejected
26+
} finally {
27+
console.log("Fetch operation has been settled (either fulfilled or rejected).");
28+
}
29+
}
30+
// Calling the async function
31+
fetchData();
32+
// Output after 2 seconds:
33+
// Success: Data fetched successfully!

0 commit comments

Comments
 (0)