Let’s say that I have this code:
JavaScript
x
13
13
1
function doSomething() {
2
const foo = await new Promise((resolve, reject) => {
3
//...
4
reject();
5
}).catch(error => {
6
//I'd like to exit the doSomething function since the promise rejected
7
return;//This only exists the this arrow funtion
8
});
9
10
console.log('Should not get to here if foo rejects');
11
}
12
13
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
:
JavaScript
1
8
1
function doSomething() {
2
const foo = await new Promise((resolve, reject) => {
3
//...
4
reject();
5
});
6
console.log('Should not get to here if foo rejects');
7
}
8
I know that I can do this, but this just feels messy:
JavaScript
1
17
17
1
function doSomething() {
2
let exitFunction = false;
3
const foo = await new Promise((resolve, reject) => {
4
//...
5
reject();
6
}).catch(error => {
7
//I'd like to exit the doSomething function since the promise rejected
8
exitFunction = true;
9
});
10
11
if (exitFunction) {
12
return;
13
}
14
15
console.log('Should not get to here if foo rejects');
16
}
17
So what is the best way to handle something like this? It’d be nice to be able to do this:
JavaScript
1
11
11
1
function doSomething() {
2
const foo = await new Promise((resolve, reject) => {
3
//...
4
reject();
5
});
6
if (foo.rejected) {
7
return;
8
}
9
console.log('Should not get to here if foo rejects');
10
}
11
Or even this:
JavaScript
1
10
10
1
function doSomething() {
2
const foo = await new Promise((resolve, reject) => {
3
//...
4
reject();
5
}).catch(error => {
6
return function2;//Sort of like JS's `break loop2;`
7
});
8
console.log('Should not get to here if foo rejects');
9
}
10
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
JavaScript
1
19
19
1
function promiseFunc() {
2
return new Promise((resolve, reject) => {
3
//...
4
reject("error!");
5
});
6
}
7
8
async function doSomething() {
9
try {
10
const foo = await promiseFunc();
11
} catch (err) {
12
console.log(err);
13
return;
14
}
15
16
console.log("Should not get to here if foo rejects");
17
}
18
19
doSomething();