带有拒绝调用的承诺构造函数与抛出错误 [英] Promise constructor with reject call vs throwing error
问题描述
在以下代码中:
var p1 = new Promise(function (resolve, reject) {抛出'test1';});var p2 = new Promise(function (resolve, reject) {拒绝('test2');});p1.catch(函数(错误){控制台日志(错误);//测试 1});p2.catch(函数(错误){控制台日志(错误);//测试 2});
使用 Promise
api 中的 reject
(在 p2
中)和抛出错误(在 p1 中)有什么区别吗?
) 使用 throw
?
完全一样吗?
如果相同,那为什么我们需要一个reject
回调?
使用
Promise
api 中的reject
(在p2
中)和抛出错误(在p1 中)有什么区别吗?
) 使用throw
?
是的,您不能异步使用throw
,而reject
是回调.例如,一些超时:
new Promise(_, 拒绝) {设置超时(拒绝,1000);});
<块引用>
完全一样吗?
不,至少当其他代码跟随您的语句时不会.throw
立即完成解析器函数,同时调用 reject
继续正常执行 - 在将承诺标记"为拒绝后.
此外,如果您throw
错误对象,引擎可能会提供不同的异常调试信息.
对于您的具体示例,您是对的,p1
和 p2
与外部无法区分.
In the following code:
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
});
Is there any difference between using reject
(in p2
) from the Promise
api, and throwing an error (in p1
) using throw
?
Its exactly the same?
If its the same, why we need a reject
callback then?
Is there any difference between using
reject
(inp2
) from thePromise
api, and throwing an error (inp1
) usingthrow
?
Yes, you cannot use throw
asynchronously, while reject
is a callback. For example, some timeout:
new Promise(_, reject) {
setTimeout(reject, 1000);
});
Its exactly the same?
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.
For your specific example, you are right that p1
and p2
are indistinguishable from the outside.
这篇关于带有拒绝调用的承诺构造函数与抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!