new Promise(function(resolve, reject){}) 的reject相当于抛异常

通过reject传异常:

<html>
    <body>
        <script>
            const promise = new Promise(function(resolve, reject) {

              if (Math.random() > 0.5){
                resolve("value");
              } else {
                reject(new Error("throw error"));
                //throw new Error("throw error")
              }
            });
            function a(v) {
                console.log("a函数");
                console.log(v);
            }
            function b(er) {
                console.log("b函数");
                console.log("reject打印Error对象",er);
            }
            promise.then(a,b)
        </script>
    </body>
</html>

控制台输出:

b函数
index.html:19 reject打印Error对象 Error: throw error
    at index.html:9:24
    at new Promise (<anonymous>)
    at index.html:4:29

 

通过throw抛异常:

<html>
    <body>
        <script>
            const promise = new Promise(function(resolve, reject) {

              if (Math.random() > 0.5){
                resolve("value");
              } else {
                //reject(new Error("throw error"));
                throw new Error("throw error")
              }
            });
            function a(v) {
                console.log("a函数");
                console.log(v);
            }
            function b(er) {
                console.log("b函数");
                console.log("打印Error对象",er);
            }
            promise.then(a,b)
        </script>
    </body>
</html>

控制台输出:

b函数
index.html:19 打印Error对象 Error: throw error
    at index.html:10:23
    at new Promise (<anonymous>)
    at index.html:4:29 

 所以有这样的等价关系:

p.then((val) => console.log('fulfilled:', val))
  .catch((err) => console.log('rejected', err));

// 等同于
p.then((val) => console.log('fulfilled:', val))
  .then(null, (err) => console.log("rejected:", err));

第一个then()方法指定的回调函数,如果运行中抛出错误,也会被catch()方法 或第二个then()方法指定的第二个回调函数 捕获。

ES6 入门教程

复习知识点:

const promise = new Promise(function(resolve, reject){})中的resolve和reject是函数指针形参,定义Promise时,还不知道resolve和reject具体是什么函数。只有执行到promise.then(a,b),才会把a函数和b函数的指针赋给new Promise中定义的resolve和reject。

resolve("value")会将字符串"value"作为参数传给a()函数,可以理解为好像是将resolve("value")替换成a("value"),resolve()像是个占位符,将来会被then()的第一个参数传入的函数(本例为a() )替换。

async await

ES6 入门教程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值