Skip to content

Commit ac27886

Browse files
refactor: async await
1 parent 082da0e commit ac27886

File tree

2 files changed

+48
-23
lines changed

2 files changed

+48
-23
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// async and await
2+
3+
// What
4+
// - async and await are keywords introduced in ES2017 (ES8) that provide a cleaner, more readable way to work with Promises and manage asynchronous code. They are essentially syntactic sugar built on top of Promises.
5+
// - async: Used to declare an asynchronous function. An async function automatically returns a Promise.
6+
// - await: Used inside an async function to pause execution until a Promise settles (resolves or rejects). It waits for the result of the Promise.
7+
8+
// Why
9+
// - The main purpose is to write asynchronous code that looks and behaves like traditional, easy-to-read synchronous code, avoiding the repetitive chaining of .then() and .catch() callbacks (Promise Chaining). This significantly improves code clarity and simplifies error handling.
10+
11+
// How
12+
// - Declare the function as async: This is mandatory for using await inside it.
13+
// - Use await before any function that returns a Promise: When the runtime encounters await, it pauses the async function, allowing other code to execute, and resumes only after the Promise resolves, returning the resolved value.
14+
// - Use try...catch for error handling: Errors (rejected Promises) are handled just like synchronous errors using standard try...catch blocks.
15+
16+
// Syntax
17+
// Function is marked as async
18+
async function myAsyncFunction() {
19+
try {
20+
// await pauses execution until the Promise resolves
21+
const result = await functionThatReturnsAPromise();
22+
console.log(result);
23+
} catch (error) {
24+
// Standard try/catch handles the rejected Promise
25+
console.error("An error occurred:", error);
26+
}
27+
}
28+
29+
// Example
30+
const promise = function () {
31+
return new Promise((resolve, reject) => {
32+
setTimeout(() => {
33+
resolve("Data fetched successfully!");
34+
reject("Error fetching data");
35+
}, 2000);
36+
});
37+
};
38+
39+
async function consumePromise() {
40+
try {
41+
const response = await promise();
42+
console.log(response);
43+
} catch (error) {
44+
console.log(error);
45+
}
46+
}
47+
48+
consumePromise();

23_asynchronous_javascript/4_async_and_await/01_async_and_await.js

Lines changed: 0 additions & 23 deletions
This file was deleted.

0 commit comments

Comments
 (0)