Question 81
Question
Describe how to implement a basic Promise polyfill.
Answer
Basic Polyfill Implementation:
Explanation:
Check for Native Promises: The
if (!Promise)
block ensures the polyfill is only executed in environments without native Promise support.Custom
Promise
Constructor: We create our ownPromise
constructor function, mimicking the behavior of the built-in one.States (
pending
,fulfilled
,rejected
): The Promise can exist in these three states to track its execution status.Queues (
resolveQueue
,rejectQueue
): These queues store callbacks that should be executed when the Promise is fulfilled or rejected. This allows us to handle asynchronous operations without blocking the main thread.resolve()
andreject()
Functions: These functions update the state of the Promise and trigger the execution of callbacks in the corresponding queue.then()
Method: The polyfill'sthen()
method accepts two optional callback functions: one for success (onFulfilled
) and one for failure (onRejected
). It returns a new Promise, which allows chaining asynchronous operations.
Important Notes:
This is a very basic polyfill. For more comprehensive coverage, consider using existing well-maintained polyfills like the one from core-js:
Last updated