这是代码:
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();
以下是日志:
error throw
runtime.ts:177 catch
runtime.ts:177 promise all catch
VM193:8 Uncaught (in promise) Error: critical error
catch 不是应该捕获 Promise 中的错误吗? 实际上,错误会通过所有捕获,但最终仍然是“未捕获”
你正在回报一个毫无保留的承诺。
for(let i = 0; i < 1; i++)
{
const promise = errorFunc();
const guarded = promise.catch(()=> console.log("catch"))
promises.push(guarded)
}
返回对预期行为的谨慎承诺。