Last updated on Sep 24, 2020 by Suraj Sharma
In this tutorial, you will learn how you can handle an error or a promise rejection in JavaScript async/await.
Consider, we have a Promise
const getAsyncOddNumber = (number) => {
return new Promise((resolve, reject) => {
setTimeout(()=>{
if(number<=0) {
reject('Number must be greater than zero');
} else {
if (number % 2 !== 0)
resolve(`${number} is an odd number`);
else
resolve(`${number} is not an odd number`);
}
}, 500);
})
}
If the number
is less than and equals to zero
, then the promise would get rejected, resulting in a JavaScript error.
const mainFn = async () => {
const message = await getAsyncOddNumber(-2);
console.log(message); // nothing gets printed
}
mainFn();
To successfully handle the error in async/await, we are going to use JavaScript try...catch
statement.
const mainFn = async () => {
try {
const message = await getAsyncOddNumber(-2);
console.log(message);
} catch(error) {
console.log(error); // 'Number must be greater than zero'
}
}
mainFn();
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.