承诺构造函数与拒绝调用vs抛出错误 [英] Promise constructor with reject call vs throwing error

查看:88
本文介绍了承诺构造函数与拒绝调用vs抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中:

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?

推荐答案


使用拒绝之间有什么区别(在 p2 )来自 Promise api,并使用 throw抛出错误(在 p1 中)

Is there any difference between using reject (in p2) from the Promise api, and throwing an error (in p1) using throw?

是的,你不能异步使用 throw ,而 reject 是一个回调。例如,一些超时:

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?

不,至少在其他代码跟随你的陈述时没有。 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抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆