Skip to content

JavaScript await Promise

  • by

In JavaScript, the await keyword is used to pause the execution of an asynchronous function until a Promise is fulfilled or rejected. It can only be used within an async function.

The basic syntax for using await with a Promise is as follows:

async function functionName() {
  try {
    const result = await promise; // Await the promise
    // Code to be executed after the promise is fulfilled
  } catch (error) {
    // Code to handle the error if the promise is rejected
  }
}
  1. The function containing the await keyword must be declared with the async keyword.
  2. The await keyword is used followed by the Promise object you want to await. It pauses the execution of the function until the Promise is fulfilled or rejected.
  3. The result of the awaited Promise is assigned to a variable (result in the example).
  4. If the Promise is fulfilled, the code after the await line will be executed. If the Promise is rejected, an error will be thrown, and the execution will jump to the catch block.
  5. You can use a try...catch block to handle any errors that occur during the await operation. The catch block will be executed if the awaited Promise is rejected, allowing you to handle the error gracefully.

Note: the await keyword can only be used inside an async function. If you try to use it outside an async function, it will result in a syntax error.

JavaScript await Promise example

Simple example code.

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { name: 'John', age: 30 };
      // Simulating a successful asynchronous operation
      resolve(data);
      // Simulating an error during the asynchronous operation
      // reject(new Error('Failed to fetch data'));
    }, 2000);
  });
}

async function getData() {
  try {
    console.log('Fetching data...');
    const result = await fetchData();
    console.log('Data:', result);
  } catch (error) {
    console.log('Error:', error.message);
  }
}

getData();

Output:

JavaScript await Promise

Another example of using await with a Promise:

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function example() {
  console.log('Start');
  await delay(2000); // Wait for 2000 milliseconds
  console.log('After waiting');
}

example();

Output:

Start
(after 2 seconds)
After waiting

Comment if you have any doubts or suggestions on this JS Asynchronous 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

Your email address will not be published. Required fields are marked *