Created
January 21, 2016 23:28
-
-
Save domenic/8ed6048b187ee8f2ec75 to your computer and use it in GitHub Desktop.
How to subclass a promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ES6 | |
| class AngularPromise extends Promise { | |
| constructor(executor) { | |
| super((resolve, reject) => { | |
| // before | |
| return executor(resolve, reject); | |
| }); | |
| // after | |
| } | |
| then(onFulfilled, onRejected) { | |
| // before | |
| const returnValue = super.then(onFulfilled, onRejected); | |
| // after | |
| return returnValue; | |
| } | |
| } | |
| // ES5 | |
| function AngularPromise(executor) { | |
| var p = new Promise(function (resolve, reject) { | |
| // before | |
| return executor(resolve, reject); | |
| }); | |
| // after | |
| p.__proto__ = AngularPromise.prototype; | |
| return p; | |
| } | |
| AngularPromise.__proto__ = Promise; | |
| AngularPromise.prototype.__proto__ = Promise.prototype; | |
| AngularPromise.prototype.then = function then(onFulfilled, onRejected) { | |
| // before | |
| var returnValue = Promise.prototype.then.call(this, onFulfilled, onRejected); | |
| // after | |
| return returnValue; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Pwuts
@heecheon92
The only thing i dont like is the fact, that the amended call stack is generated, wether used or not. And stack traces are very heavy objects in any javascript engine. So there is super heavy performance bottleneck. We can defer the stack trace generation.
The result is also closer to Promise.withResolvers()
output on my machine: