#atom
Content:
The async
and await
keywords in JavaScript provide a modern and syntactically cleaner way to work with asynchronous code. They are built on top of Promises and allow you to write asynchronous code that looks and behaves like synchronous code, making it easier to read and maintain.
Key Concepts:
-
async
Functions:- An
async
function is a function declared with theasync
keyword. - It automatically returns a Promise. If the function returns a value, the Promise is resolved with that value. If the function throws an error, the Promise is rejected.
- Example:
async function fetchData() { return "Data fetched!"; } fetchData().then((result) => console.log(result)); // "Data fetched!"
- An
-
await
Keyword:- The
await
keyword can only be used inside anasync
function. - It pauses the execution of the
async
function until the Promise it is waiting for is resolved or rejected. - If the Promise is resolved,
await
returns the resolved value. If the Promise is rejected, it throws an error, which can be caught usingtry/catch
. - Example:
async function fetchData() { const response = await fetch("https://api.example.com/data"); const data = await response.json(); return data; }
- The
-
Error Handling:
- Errors in
async
functions can be handled usingtry/catch
blocks, similar to synchronous code. - Example:
async function fetchData() { try { const response = await fetch("https://api.example.com/data"); if (!response.ok) { throw new Error("Network response was not ok"); } const data = await response.json(); return data; } catch (error) { console.error("Error fetching data:", error); } }
- Errors in
-
Sequential vs Concurrent Execution:
await
can be used to run asynchronous operations sequentially or concurrently.- Sequential Execution:
async function sequential() { const result1 = await fetchData1(); const result2 = await fetchData2(); return [result1, result2]; }
- Concurrent Execution:
async function concurrent() { const promise1 = fetchData1(); const promise2 = fetchData2(); const [result1, result2] = await Promise.all([promise1, promise2]); return [result1, result2]; }
-
Top-Level
await
:- In modern JavaScript environments (e.g., ES modules),
await
can be used at the top level of a module without needing anasync
function. - Example:
const data = await fetchData(); console.log(data);
- In modern JavaScript environments (e.g., ES modules),
Example: Fetching Data with async/await
async function fetchUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error("User not found");
}
const userData = await response.json();
return userData;
} catch (error) {
console.error("Error fetching user data:", error);
}
}
fetchUserData(1).then((user) => console.log(user));
Example: Combining async/await
with Promises
async function processData() {
const data = await fetchData();
const processedData = await process(data);
return saveData(processedData);
}
processData()
.then(() => console.log("Data processed and saved!"))
.catch((error) => console.error("Error:", error));
Benefits of async/await
:
- Readability: Code is easier to read and understand compared to nested Promises or callbacks.
- Error Handling: Errors can be handled using
try/catch
, making it similar to synchronous error handling. - Debugging: Debugging is easier because the code looks like synchronous code.
Linked Cards:
- Promises in JavaScript:
async/await
is built on top of Promises. - Functions in JavaScript:
async
functions are a special type of function. - Error Handling in JavaScript:
try/catch
is used for error handling inasync/await
. - Asynchronous JavaScript:
async/await
is a modern approach to handling async tasks. - Control Structures in JavaScript:
async/await
simplifies control flow in asynchronous code.
Tags: #JavaScript #AsyncAwait #AsynchronousProgramming #Promises #ErrorHandling #ControlFlow
Connections:
Sources: