Callbacks and Promises and async / await and promises.all and promises.race and fetch
Async and Await in JavaScript is used to simplify handling asynchronous operations using promises. By enabling asynchronous code to appear synchronous, they enhance code readability and make it easier to manage complex asynchronous flows.
In JavaScript, asynchronous operations allow you to handle tasks that take time to complete (e.g., API calls, file reading, or timers) without blocking the main thread. Here are the key concepts and tools for working with async operations:
- callbacks
- Promises
- async / await
- promises.all and promises.race
- fetch
1. Callbacks
A callback function is passed as an argument to another function and is executed after the asynchronous operation completes.
Example:
console.log("Start");
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
console.log("End");
Output:
Start
End
This runs after 2 seconds
Issues with Callbacks:
- Callback Hell: Nested callbacks become hard to read and maintain.
- Debugging is difficult.
Sponsor Key-Word
"This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication"
2. Promises
A Promise represents a value that will eventually resolve (success) or reject (failure). It helps avoid deeply nested callbacks.
States of a Promise:
- Pending: Initial state.
- Fulfilled: Operation was successful (
resolve()
). - Rejected: Operation failed (
reject()
).
Example:
console.log("Start");
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data loaded successfully!");
}, 2000);
});
fetchData
.then((result) => {
console.log(result); // Success case
})
.catch((error) => {
console.error(error); // Failure case
});
console.log("End");
Output:
Start
End
Data loaded successfully!
Sponsor Key-Word
"This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication"
3. async
/ await
async
async
function allows us to write promise-based code as if it were synchronous. This ensures that the execution thread is not blocked. Async functions always return a promise. If a value is returned that is not a promise, JavaScript automatically wraps it in a resolved promise.await
await
keyword is used to wait for a promise to resolve. It can only be used within an async block. Await makes the code wait until the promise returns a result, allowing for cleaner and more manageable asynchronous code.async
and await
simplify working with promises. They make asynchronous code look synchronous and readable.
Rules:
async
functions always return a Promise.await
can only be used inside anasync
function.
Example:
console.log("Start");
async function loadData() {
try {
const result = await new Promise((resolve) => {
setTimeout(() => resolve("Data fetched!"), 2000);
});
console.log(result);
} catch (error) {
console.error(error);
}
}
loadData();
console.log("End");
Output:
Start
End
Data fetched!
Sponsor Key-Word
"This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication"
Advantages of Async and Await
- Improved Readability: Async and Await allow asynchronous code to be written in a synchronous style, making it easier to read and understand.
- Error Handling: Using try/catch blocks with async/await simplifies error handling.
- Avoids Callback Hell: Async and Await prevent nested callbacks and complex promise chains, making the code more linear and readable.
- Better Debugging: Debugging async/await code is more intuitive since it behaves similarly to synchronous code.
4. Promise.all
and Promise.race
Promise.all
Runs multiple promises in parallel and waits for all of them to resolve (or rejects if one fails).
const promise1 = new Promise((resolve) => setTimeout(() => resolve("One"), 1000));
const promise2 = new Promise((resolve) => setTimeout(() => resolve("Two"), 2000));
Promise.all([promise1, promise2])
.then((results) => console.log(results)) // ['One', 'Two']
.catch((error) => console.error(error));
Promise.race
Returns the first promise that resolves or rejects.
Promise.race([promise1, promise2])
.then((result) => console.log(result)) // 'One' (faster)
.catch((error) => console.error(error));
Sponsor Key-Word
"This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication"
5. Using fetch
for API Calls
The fetch
API is a common way to make HTTP requests.
Example with async/await
:
async function fetchData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData();
Summary of Key Tools:
- Callbacks: Basic method, but leads to callback hell.
- Promises: Better structure to handle async operations.
async/await
: Cleaner syntax for Promises.- Promise.all / Promise.race: Handle multiple promises.
fetch
API: Simplifies HTTP requests.
Sponsor Key-Word
"This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication"
Comments
Post a Comment