JavaScript Async and Await — Your Asynchronous Buddies
The async
and await
keywords help us in handling Promises more conveniently and it is more readable than regular promise handling using then()
and catch()
.
Let’s see how we consume Promises using .then()
and .catch()
.
let flag = true;let promise = new Promise((resolve, reject) => {
setTimeout(() => {
if(flag) resolve('I am resolved');
else reject(new Error('I am rejected'));
}, 1000);
});promise.then(res => console.log(res)).catch(err => console.log(err));
// I am resolved
The above Promise can be consumed by using async
and await
like below.
async function demo() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('I am resolved');
}, 1000);
});
let res = await promise;
console.log(res); // I am resolved
}demo();
The
await
keyword should only be used inside anasync
function.
The async keyword
If we use async
before any function then the function will return a Promise. If the function is not returning any Promise explicitly then it will wrap a Promise around the return value implicitly. Let’s see one example.
async function greet() {
return 'Welcome';
}greet().then(res => console.log(res));
// Welcome
The await keyword
The await
keyword waits for a Promise and pauses the code in that line until the Promise gets resolved. Remember the await keyword should always be used inside the async
function otherwise, it will throw an error.
async function foo() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('I am resolved');
}, 1000);
});let res = await promise;
console.log(res);
console.log('end');
}foo();
// I am resolved
// end
Here the code execution gets paused in the line where await
is used and resumes when the Promise resolves. Therefore after 1 second when the Promise will resolve, the console statements will be printed.
Handling Errors
We can use the try…catch block to handle errors in async
/ await
.
async function foo() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('I am rejected'));
}, 1000);
});try {
let res = await promise;
console.log(res);
} catch (e) {
console.log(e);
}
}foo();
// Error: I am rejected