Here is the code:
function sleep(ms:number)
{
return new Promise((resolve:any,reject:any) => setTimeout(resolve,ms))
}
async function errorFunc(): Promise<void>
{
await sleep(2000)
console.log("error throw")
throw new Error("critical error");
}
let promises: Promise<void>[] = []
for(let i = 0; i < 1; i++)
{
const promise = errorFunc();
promise.then(()=>console.log("then"))
promise.catch(()=> console.log("catch"))
promises.push(promise)
}
async function main()
{
await Promise.all(promises).catch((e)=>console.log("promise all catch"))
}
main();
"use strict";
function sleep(ms) {
return new Promise((resolve, reject) => setTimeout(resolve, ms));
}
async function errorFunc() {
await sleep(2000);
console.log("error throw");
throw new Error("critical error");
}
let promises = [];
for (let i = 0; i < 1; i++) {
const promise = errorFunc();
promise.then(() => console.log("then"));
promise.catch(() => console.log("catch"));
promises.push(promise);
}
async function main() {
await Promise.all(promises).catch((e) => console.log("promise all catch"));
}
main();
Here are logs:
error throw
runtime.ts:177 catch
runtime.ts:177 promise all catch
VM193:8 Uncaught (in promise) Error: critical error
Isn’t the catch supposed to catch an error in Promise?
And actually, error passes through all catches but still at the end "Uncaught"
2
Answers
You’re returning an unguarded promise.
Return a guarded promise for the expected behavior.
Note:
promise.then(() => console.log("then"));
will be returning a new Promise, this promise is then just dangling, it’s neither been returned to anything, or handled. Also note, it’s the same for.catch
it will also be returning a promise that’s just dangles, although less likely to cause an issue unless another error is thrown inside the catch.Like other languages if you want to catch an error, and then continue to propagate this error, what you normally do is re-raise the error. And this is exactly what you can do with promises.
example, notice how the error is re-thrown, and how everything is a single promise chain.