Build a Promise from scratch

Build a Promise class from scratch  (DOM API) [Hard, Robinhood, Zillow, Video]

The above code defines a custom implementation of the Promise class in JavaScript called MyPromise. The MyPromise constructor function takes an executor function as its argument, which in turn takes two functions - resolve and 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.

The MyPromise class has three possible states - PENDING, SUCCESS, and REJECTED - which are defined in the STATE object. The #value and #state private fields of the MyPromise instance are used to store the result and state of the promise, respectively. The #successCallbacks and #rejectedCallbacks private fields are used to store the success and error callbacks registered by then and catch functions.

The 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.

The 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 fooA and fooB are defined that return a new instance of MyPromise. When fooA is called with the value of -1, it rejects with the reason 'Cannot use -1'. The then and catch functions are used to handle the response and error, respectively, of the MyPromise returned by fooA.

Complete and Continue  
Discussion

0 comments