问题描述
在以下代码中:
var p1 = new Promise(function (resolve, reject) {
throw 'test1';
});
var p2 = new Promise(function (resolve, reject) {
reject('test2');
});
p1.catch(function (err) {
console.log(err); // test1
});
p2.catch(function (err) {
console.log(err); // test2
});
使用拒绝
之间是否有任何区别( in p2
)来自 Promise
api,并抛出错误(在 p1
)使用抛出
?
Is there any difference between using reject
(in p2
) from the Promise
api, and throwing an error (in p1
) using throw
?
它完全一样吗?
如果相同,为什么我们需要拒绝
回调?
If its the same, why we need a reject
callback then?
推荐答案
是的,你异步使用 throw
,而 reject
是一个回调。例如,一些超时:
Yes, you cannot use throw
asynchronously, while reject
is a callback. For example, some timeout:
new Promise(_, reject) {
setTimeout(reject, 1000);
});
不,至少在其他代码跟随你的陈述时没有。 throw
立即完成解析器功能,同时调用 reject
继续正常执行 - 将承诺标记为已拒绝。
No, at least not when other code follows your statement. throw
immediately completes the resolver function, while calling reject
continues execution normally - after having "marked" the promise as rejected.
此外,如果抛出
错误对象,引擎可能会提供不同的异常调试信息。
Also, engines might provide different exception debugging information if you throw
error objects.
对于您的具体示例,您是正确的 p1
和 p2
无法区分外面。
For your specific example, you are right that p1
and p2
are indistinguishable from the outside.
这篇关于承诺构造函数与拒绝调用vs抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!