Because there's no reason it shouldn't. The return
is in a callback function, so it only returns from that callback function. It does reject the outer promise, but doing that doesn't prevent the remainder of the code in your promise executor (the function you pass new Promise
) from continuing.
There are several problems with the code shown, though.
If you already have a promise, you don't need to create a new one. In a
, for instance, you have the promise from ab
, so there's no reason for new Promise
. This is often called the explicit Promise creation antipattern, this question's answers go into detail.
Using await
in a promise executor function generally doesn't make much sense and probably means the executor is doing too much. The purpose of a promise executor is to start an asynchronous process, not to wait for one.
Using .catch
/.then
/.finally
inside an async
function is generally not best practice; just use await
and try
/catch
.
Your a
function should probably be just:
const a = async () => {
try {
await ab();
// Or you might put the `console.log`s here, there are
// reasons for each, but it doesn't matter given we're
// rethrowing the error
} catch (err) {
console.log("error")
throw err;
}
console.log("A")
console.log("B")
};
That will reject the promise a
returns when ab
's promise rejects, using the same rejection reason, and terminate a
's logic rather than allowing it to continue; if ab
's promise doesn't reject, it will run the two console.log
statements.
Live Example:
const a = async () => {
try {
await ab();
// Or you might put the `console.log`s here, there are
// reasons for each, but it doesn't matter given we're
// rethrowing the error
} catch (err) {
console.log("error")
throw err;
}
console.log("A")
console.log("B")
};
function ab() {
return new Promise((resolve, reject) => {
return reject("a");
});
}
async function e() {
try {
await a();
} catch (e) {
console.log(e);
}
}
e();