Promise 的一些扩展方法

, in 编程#JavaScript
// promise.done() Promise.prototype.done = function (onFulfilled, onRejected) { this.then(onFulfilled, onRejected).catch(function (reason) { // 抛出一个全局错误 setTimeout(() => { throw reason; }, 0); }); }; // promise.finally() Promise.prototype.finally = function (callback) { let P = this.constructor; return this.then( (value) => P.resolve(callback()).then(() => value), (reason) => P.resolve(callback()).then(() => { throw reason; }), ); }; // promise.if() Promise.prototype.if = function (flag, planAS, planBS) { return flag ? Promise.all(planAS.map((f) => f())) : Promise.all(planBS.map((f) => f())); };
£ 赞赏