1. The async and await keywords in JavaScript are used to work with asynchronous operations in a more synchronous-like manner. Here's a simple example demonstrating the use of async and await:
// Asynchronous function that returns a promise
function fetchData() {
return new Promise(resolve => {
// Simulate an asynchronous operation (e.g., fetching data from an API)
setTimeout(() => {
const data = 'Async data received!';
resolve(data);
}, 2000); // Simulating a 2-second delay
});
}
// Asynchronous function using async/await
async function fetchDataAsync() {
try {
// Using the await keyword to wait for the promise to resolve
const result = await fetchData();
console.log(result);
} catch (error) {
console.error('Error:', error);
}
}
// Call the async function
fetchDataAsync();
In this example:
The fetchData function returns a Promise that resolves after a simulated 2-second delay. This function could represent an asynchronous operation, such as fetching data from an API.
The fetchDataAsync function is marked as async, allowing the use of the await keyword inside it. Inside the function, await is used to wait for the fetchData promise to resolve.
When the promise from fetchData resolves, the result is logged to the console. If there is an error (e.g., a rejected promise), it is caught in the catch block.
Finally, the fetchDataAsync function is called, initiating the asynchronous operation.
This example showcases how async and await simplify working with promises and asynchronous code, making it appear more like traditional synchronous code.
2. Promise.all() javscript example
Promise.all() is a useful method in JavaScript for handling multiple promises concurrently. It takes an array of promises as input and returns a new promise that fulfills with an array of the resolved values when all the input promises have been resolved. If any of the input promises is rejected, the returned promise is immediately rejected with the reason of the first rejected promise.
Here's an example demonstrating the usage of Promise.all():
javascript
Copy code
// Simulated asynchronous functions returning promises
function fetchData1() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data from fetchData1');
}, 2000);
});
}
function fetchData2() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data from fetchData2');
}, 1500);
});
}
function fetchData3() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Simulating an error
reject('Error from fetchData3');
}, 1000);
});
}
// Using Promise.all() to handle multiple promises
async function fetchDataConcurrently() {
try {
const results = await Promise.all([fetchData1(), fetchData2(), fetchData3()]);
// If all promises resolve, results will be an array of their resolved values
console.log('All promises resolved:', results);
} catch (error) {
// If any promise is rejected, the error will be caught here
console.error('Error:', error);
}
}
// Call the function to initiate the concurrent fetching
fetchDataConcurrently();
In this example:
fetchData1, fetchData2, and fetchData3 are asynchronous functions that return promises.
The fetchDataConcurrently function uses Promise.all() to concurrently execute these promises.
The await keyword is used to wait for the completion of all promises passed to Promise.all().
If all promises resolve successfully, the results array will contain the resolved values from each promise.
If any of the promises is rejected, the error will be caught in the catch block.
This allows for efficient handling of multiple asynchronous operations, especially when you need to wait for all of them to complete before proceeding.
Comments
Post a Comment