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
}
}
- The function containing the
awaitkeyword must be declared with theasynckeyword. - The
awaitkeyword is used followed by thePromiseobject you want to await. It pauses the execution of the function until thePromiseis fulfilled or rejected. - The result of the awaited
Promiseis assigned to a variable (resultin the example). - If the
Promiseis fulfilled, the code after theawaitline will be executed. If thePromiseis rejected, an error will be thrown, and the execution will jump to thecatchblock. - You can use a
try...catchblock to handle any errors that occur during theawaitoperation. Thecatchblock will be executed if the awaitedPromiseis 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:

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