V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Vrds
V2EX  ›  JavaScript

Promise 如何链式调用的?

  •  
  •   Vrds · 221 天前 · 984 次点击
    这是一个创建于 221 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Promise.resolve()
        .then(() => {          // then1
            throw "err1";
        })
        .then(() => {          // then2
    
        }) 
        .catch((reason) => {   // catch1
            console.log(reason);
            throw "err2";
        })
        .catch((reason) => {   // catch2
        	console.log(reason);
        });
        
    

    如上面代码,then2 回调虽然不执行,但是如何跳到 catch2 的?

    9 条回复    2023-09-19 22:21:25 +08:00
    blackrabbit
        1
    blackrabbit  
       221 天前
    then1 抛出错误,Promise 状态为 rejected ,会跳过 then2 直接进入 catch1 ,而 catch1 又抛出 err2 ,所以进入 catch2
    DOLLOR
        2
    DOLLOR  
       221 天前
    如果你时想了解 promise 的实现原理,可以去参考 bluebird 的实现:
    https://github.com/petkaantonov/bluebird
    ochatokori
        3
    ochatokori  
       221 天前 via Android
    then2 和 catch2 并没有直接关系,catch2 的服务对象是 catch1 返回的 promise
    Mutoo
        4
    Mutoo  
       221 天前   ❤️ 1
    1) .catch(fn) 只是 .then(null, fn) 的语法糖
    2) 根据 https://github.com/promises-aplus/promises-spec 的第 7.II 条,then 会产生新的 promise ,当 onRejected 抛出异常的时候,新产生的 promise 会把新抛出的异常传递下去。而 7.III 如果 onRejected 没有返回值或抛异常,则将原来有状态传递下去。

    另外可以参考一下 promise a+ 的 ployfill ,实现也就不到 200 行。
    Vrds
        5
    Vrds  
    OP
       221 天前
    @Mutoo 好的,感谢指点!
    Vrds
        6
    Vrds  
    OP
       221 天前
    @blackrabbit 感谢指点
    Vrds
        7
    Vrds  
    OP
       221 天前
    @DOLLOR 感谢指点
    Vrds
        8
    Vrds  
    OP
       221 天前
    @ochatokori 感谢指点
    mrcode
        9
    mrcode  
       221 天前
    虽然老生常谈了,promise.then 的回调函数返回值会被不停的解析,直到非 promise 值出现
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2931 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:41 · PVG 22:41 · LAX 07:41 · JFK 10:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.