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


    通过reject传异常:

    1. <body>
    2. <script>
    3. const promise = new Promise(function(resolve, reject) {
    4. if (Math.random() > 0.5){
    5. resolve("value");
    6. } else {
    7. reject(new Error("throw error"));
    8. //throw new Error("throw error")
    9. }
    10. });
    11. function a(v) {
    12. console.log("a函数");
    13. console.log(v);
    14. }
    15. function b(er) {
    16. console.log("b函数");
    17. console.log("reject打印Error对象",er);
    18. }
    19. promise.then(a,b)
    20. script>
    21. body>

    控制台输出:

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

     

    通过throw抛异常:

    1. <body>
    2. <script>
    3. const promise = new Promise(function(resolve, reject) {
    4. if (Math.random() > 0.5){
    5. resolve("value");
    6. } else {
    7. //reject(new Error("throw error"));
    8. throw new Error("throw error")
    9. }
    10. });
    11. function a(v) {
    12. console.log("a函数");
    13. console.log(v);
    14. }
    15. function b(er) {
    16. console.log("b函数");
    17. console.log("打印Error对象",er);
    18. }
    19. promise.then(a,b)
    20. script>
    21. body>

    控制台输出:

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

     所以有这样的等价关系:

    1. p.then((val) => console.log('fulfilled:', val))
    2. .catch((err) => console.log('rejected', err));
    3. // 等同于
    4. p.then((val) => console.log('fulfilled:', val))
    5. .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 入门教程

  • 相关阅读:
    -钞票兑换-
    Hive日分区表如何快速导入到StarRocks
    尚好房 07_前端房源展示
    探讨大型公共建筑能耗监测与信息管理系统研究及应用
    Android Jetpack架构组件库:Hilt
    尚硅谷Vue系列教程学习笔记(6)
    Windows 11 电脑黑屏 + Office软件打不开?
    2022年服贸会:偶数科技参加Web3.0发展趋势高峰论坛
    流向算法(FDA)(Matlab代码实现)
    RuoYi 若依后台管理系统存在SQL注入漏洞CVE-2023-49371
  • 原文地址:https://blog.csdn.net/qq_27361945/article/details/128113533