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

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

问题描述

在以下代码中:

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错误对象,引擎可能会提供不同的异常调试信息.

对于您的具体示例,您是对的,p1p2 与外部无法区分.

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 (in p2) from the Promise api, and throwing an error (in p1) using throw?

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屋!

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