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
await
keyword must be declared with theasync
keyword. - The
await
keyword is used followed by thePromise
object you want to await. It pauses the execution of the function until thePromise
is fulfilled or rejected. - The result of the awaited
Promise
is assigned to a variable (result
in the example). - If the
Promise
is fulfilled, the code after theawait
line will be executed. If thePromise
is rejected, an error will be thrown, and the execution will jump to thecatch
block. - You can use a
try...catch
block to handle any errors that occur during theawait
operation. Thecatch
block will be executed if the awaitedPromise
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:
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