I have worked with Promises in Javascript and I am trying to implement my functions in async-await . How do I trigger a reject() which will be caught in .catch() in async-await
In promises we have a way to manually trigger a reject() :
const doSomething = (someNumber)=>{
return new Promise((resolve,reject)=>{
if (someNumber > 5) {
resolve('this resolves when someNumber is greater than 5')
}else{
reject('this gives a reject when someNumber is not greater than 5')
}
})
}
doSomething(7)
.then((infoMessage)=>{
//this will show
console.log(infoMessage)
})
.catch((err)=>{
//this wont show
console.log(errMessage)
})
doSomething(3)
.then((infoMessage)=>{
//this wont show
console.log(infoMessage)
})
.catch((err)=>{
//this will show
console.log(errMessage)
})
Just throw the error:
async function rejectMe() {
throw new Error("rejected!");
}
async function main() {
await rejectMe();
}
main()
.then(() => {
console.log("finished!")
})
.catch((e) => {
console.error(e);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With