Ale*_*lex -1 javascript promise ecmascript-next
ES2018之前,我曾经窝额外then的承诺链的末端,每当我不得不执行任何清理逻辑,我想重复,否则在then和catch更高,如
new Promise(
(res, rej) => setTimeout(() => rej({}), 1000)
).then(
res => console.log(res)
).catch(
err => console.error(err)
).then(
() => console.log('Finally')
)Run Code Online (Sandbox Code Playgroud)
但是现在finally已经在Promise原型上添加了,我看不出它then与上述方法中的最后一个有什么不同.以下将产生相同的输出.
new Promise(
(res, rej) => setTimeout(() => rej({}), 1000)
).then(
res => console.log(res)
).catch(
err => console.error(err)
).finally(
() => console.log('Finally')
)Run Code Online (Sandbox Code Playgroud)
难道finally仅仅是服务于本地无极API在语义的目的是什么?
一个then当承诺被拒绝回调不执行-这可能发生,即使通过返回的一个承诺catch调用:在其回调抛出或返回拒绝承诺.err => console.error(err)是可能不会做,但你永远不知道.
同样,我会建议有利于.then(…, …)过.then(…).catch(…),如果你只是想从当初的诺言处理错误,而不是从then回调.我会写的
promise.then(console.log, console.error).finally(() => console.log('Finally'));
Run Code Online (Sandbox Code Playgroud)
签名中存在其他或多或少明显的差异:finally回调不接收任何参数,并且p.finally()返回将以相同的结果实现/拒绝的承诺p(除非在回调中存在异常或返回拒绝).
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |