我有下面的代码,我希望在我的控制台中首先有hi
,然后是error
,最后是why
,但结果是:hi
,然后是why
,最后一个是error
,所以我想知道,为什么会发生这种情况?
代码:
const test = new Promise((resolve, reject) => {
console.log("hi");
throw new Error("error");
})
test.finally(() => {
console.log("why")
})
我有下面的代码,我希望在我的控制台中首先有hi
,然后是error
,最后是why
,但结果是:hi
,然后是why
,最后一个是error
,所以我想知道,为什么会发生这种情况?
代码:
const test = new Promise((resolve, reject) => {
console.log("hi");
throw new Error("error");
})
test.finally(() => {
console.log("why")
})
我希望首先有
hi
在我的控制台然后错误和在结束why
你会得到if个你处理拒绝promise ,像这样:
const test = new Promise((resolve, reject) => {
console.log("hi");
throw new Error("error");
});
test
.catch((error) => console.error(error))
.finally(() => {
console.log("why")
});
...但是你的代码并没有处理拒绝,所以直到环境中未处理的拒绝代码启动,直到所有显式处理promise的代码都执行完之后,才会报告拒绝.
正如你在注释中所说的,new Promise
和你传递给它的函数的执行都是同步的,但是在该函数中抛出的错误并不是未处理的,而是由Promise
构造函数处理并转换为promise拒绝(later,未处理).
所以顺序是:
hi
finally
的处理器finally
handler
why
finally
人创造的promise