链式调用
每次的promise的回调执行都会返回一个新的promise。
按照老式的回调会导致出现难以理解的代码。如下
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
但是相比之下如果用promis则会
doSomething().then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
代码可读性大幅上升,且对于统一的失败回调,末尾用一个catch就能搞定了。
如果加上箭头函数
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);
简洁明了,看着非常舒服。
promise的错误传递
,在promise链中一旦有抛出错误,就会直接调用链中的catch,无论catch在链中距离错误产生的函数多远,这也是能在末尾catch的原因。
promise的拒绝事件
在promise被拒绝时会向全局派送事件,通常是window,具体如下:
rejectionhandled
当 Promise 被拒绝、并且在 reject 函数处理该 rejection 之后会派发此事件。
unhandledrejection
当 Promise 被拒绝,但没有提供 reject 函数来处理该 rejection 时,会派发此事件。