Skip to content

Async await JavaScript

  • by

In JavaScript, async/await is a powerful feature that allows you to write asynchronous code in a more synchronous and readable manner.

Here’s the syntax for using async/await in JavaScript:

Declaring an async function:

async function functionName() {
  // Function body
}

Using await to pause execution until a promise is resolved or rejected:

await promise;

Handling errors using try/catch:

try {
  // Awaited code or synchronous code that can throw an error
} catch (error) {
  // Error handling code
}

Calling an async function and handling the returned promise:

asyncFunction()
  .then(result => {
    // Handle the resolved value
  })
  .catch(error => {
    // Handle any errors
  });

The async keyword is used to define an asynchronous function. An asynchronous function returns a promise implicitly, which allows it to use the await keyword within its body. The await keyword is used to pause the execution of an asynchronous function until a promise is fulfilled or rejected, and then it resumes the execution and returns the resolved value.

Async await JavaScript example

Simple example code that demonstrates the usage of async/await in JavaScript:

// Function that returns a promise resolving after a given delay
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Asynchronous function using async/await
async function processData() {
  try {
    console.log('Start');

    // Pause execution for 2 seconds
    await delay(2000);

    console.log('After waiting for 2 seconds');

    // Pause execution for 1 second
    await delay(1000);

    console.log('After waiting for another second');

    // Simulating an API call
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();

    console.log('Received data:', data);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Call the asynchronous function
processData();

Output:

Async await JavaScript

Here’s a complete example demonstrating the syntax:

async function fetchUserData() {
  try {
    const response = await fetch('https://api.example.com/userdata');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching user data:', error);
  }
}

fetchUserData();

Comment if you have any doubts or suggestions on this Js Async topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading