Promise 如何链式调用的?

275 天前
 Vrds
Promise.resolve()
    .then(() => {          // then1
        throw "err1";
    })
    .then(() => {          // then2

    }) 
    .catch((reason) => {   // catch1
        console.log(reason);
        throw "err2";
    })
    .catch((reason) => {   // catch2
    	console.log(reason);
    });
    

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

1047 次点击
所在节点    JavaScript
9 条回复
blackrabbit
275 天前
then1 抛出错误,Promise 状态为 rejected ,会跳过 then2 直接进入 catch1 ,而 catch1 又抛出 err2 ,所以进入 catch2
DOLLOR
274 天前
如果你时想了解 promise 的实现原理,可以去参考 bluebird 的实现:
https://github.com/petkaantonov/bluebird
ochatokori
274 天前
then2 和 catch2 并没有直接关系,catch2 的服务对象是 catch1 返回的 promise
Mutoo
274 天前
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
274 天前
@Mutoo 好的,感谢指点!
Vrds
274 天前
@blackrabbit 感谢指点
Vrds
274 天前
@DOLLOR 感谢指点
Vrds
274 天前
@ochatokori 感谢指点
mrcode
274 天前
虽然老生常谈了,promise.then 的回调函数返回值会被不停的解析,直到非 promise 值出现

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/975311

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX