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

  • 相关阅读:
    Springboot发送邮件
    文件夹名称中空格如何替换为符号
    AIE双三唑桥联荧光环糊精分子/β-环糊精包覆肼二水杨腙聚集诱导发光微球的制备
    PyTorch构建训练集
    Spark SQL
    IOS输入框聚焦会把内容区域顶起
    leecode959. 由斜杠划分区域
    常用的排序算法的时间复杂度以及稳定性
    FTP传输安全问题日渐突出,如何解决替代问题?
    Flir Blackfly S USB3 工业相机:白平衡设置方法
  • 原文地址:https://blog.csdn.net/qq_27361945/article/details/128113533