Build a Promise from scratch
Build a Promise class from scratch (DOM API) [Hard, Robinhood, Zillow, Video]
reject - as arguments. The
resolve function is called with a value if the promise is fulfilled, and the
reject function is called with a reason if the promise is rejected. The
then function is used to register callbacks that will be called when the promise is fulfilled, while the
catch function is used to register callbacks that will be called when the promise is rejected.
MyPromise class has three possible states - PENDING, SUCCESS, and REJECTED - which are defined in the
STATE object. The
#state private fields of the
MyPromise instance are used to store the result and state of the promise, respectively. The
#rejectedCallbacks private fields are used to store the success and error callbacks registered by
then function returns a new
MyPromise instance, which allows for chaining of multiple
then functions. When the
then function is called, it checks the state of the promise. If the promise is pending, it adds the success and error callbacks to their respective lists. If the promise is already fulfilled or rejected, it immediately calls the corresponding callback.
catch function is used to handle errors thrown by the
then function, and it simply returns a new
MyPromise instance with the error callback registered.
Finally, two asynchronous functions
fooB are defined that return a new instance of
fooA is called with the value of -1, it rejects with the reason 'Cannot use -1'. The
catch functions are used to handle the response and error, respectively, of the
MyPromise returned by