Let’s say that I have this code:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
//I'd like to exit the doSomething function since the promise rejected
return;//This only exists the this arrow funtion
});
console.log('Should not get to here if foo rejects');
}
If foo returns a rejected promise, then I’d like to exit doSomething(), but the code above does not do this. Instead since the error is caught, the code continues.
If I do not catch the rejected promise then I get an error: UnhandledPromiseRejectionWarning:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
});
console.log('Should not get to here if foo rejects');
}
I know that I can do this, but this just feels messy:
function doSomething() {
let exitFunction = false;
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
//I'd like to exit the doSomething function since the promise rejected
exitFunction = true;
});
if (exitFunction) {
return;
}
console.log('Should not get to here if foo rejects');
}
So what is the best way to handle something like this? It’d be nice to be able to do this:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
});
if (foo.rejected) {
return;
}
console.log('Should not get to here if foo rejects');
}
Or even this:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
return function2;//Sort of like JS's `break loop2;`
});
console.log('Should not get to here if foo rejects');
}
Does anyone else feel my pain, if so what are is the best (cleanest) way to handle this?
Advertisement
Answer
I suggest using try/catch if you handle promises in async function
function promiseFunc() {
return new Promise((resolve, reject) => {
//...
reject("error!");
});
}
async function doSomething() {
try {
const foo = await promiseFunc();
} catch (err) {
console.log(err);
return;
}
console.log("Should not get to here if foo rejects");
}
doSomething();