• 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 入门教程

  • 相关阅读:
    Maven 工具学习笔记(基础)
    Elastic Stack从入门到实践(一)--Elastic Stack入门(2)--Beats、Filebea入门
    2023届双非硕士四个月秋招历程总结
    Sharding-JDBC源码解析与vivo的定制开发
    Windows server 2012远程桌面会话主机和远程桌面授权
    体感互动游戏VR游戏AR体感游戏软件开发
    shiro授权-SSM
    Springboot 连接 Mysql
    三、支付宝支付对接 - 申请、配置、签约、获取RSkey(1)
    正则表达式(Java)
  • 原文地址:https://blog.csdn.net/qq_27361945/article/details/128113533