How to use async/await In Javascript

Async/await is a programming technique that streamlines asynchronous operations, allowing code to pause and resume tasks .It also simplifies asynchronous programming, by handling tasks one step at a time, enhancing code readability and responsiveness.

Syntax

async function executeTasks(tasks) {
try {
const taskResults = await Promise.all(tasks);

// Handle the successful completion of tasks here
} catch (taskError) {

// Handle errors that occurred during task execution here
}
}
const tasks = [fetchData(), saveData()];
executeTasks(tasks);

Example: In this example, we will implement a code to handle errors by using async/await syntax.

Javascript




async function handlePromises(promises) {
    try {
        const results = await Promise.all(promises);
        console.log('Successful results:', results);
    } catch (error) {
        console.error('Error occurred:', error);
    }
}
  
function fetchData() {
    return new Promise((resolve) =>
        setTimeout(() => resolve('Data Fetched'), 1000));
}
  
function saveData() {
    return new Promise((resolve) =>
        setTimeout(() => resolve('Data Saved'), 500));
}
  
const promises = [fetchData(), saveData()];
handlePromises(promises);


Output:

Successful results: [ 'Data Fetched', 'Data Saved' ]


How to handle errors in Promise.all ?

In this article, we will see how to handle errors with promise.all( ) function. When working with Promise. all in JavaScript, it’s essential to handle errors properly to ensure your application’s robustness and reliability. Promise.all is all or nothing. It resolves once all promises in the array are resolved, or rejected as soon as one of them is rejected. In other words, it either resolves with an array of all resolved values or rejects with a single error. If any of the promises within the array is rejected, the Promise.all itself will reject. Here’s how you can handle errors in Promise. all.

Table of Content

  • Using .then() and .catch() Method
  • Using async/await

Similar Reads

Using .then() and .catch() Method

The .then() method can be used to define what should happen when a Promise successfully resolves, allowing you to specify the next steps in your code. The .catch() method can be utilized when a Promise encounters an error or is rejected, .catch() is employed to handle the error gracefully, letting you manage and log the error that occurred....

Using async/await

...