Q24: Implement a simplified polyfill for Promise.resolve().
Answer
Promise.resolve(value) returns a promise that adopts the supplied value's state. If the value is a promise or thenable, the returned promise adopts its eventual outcome.
function myPromiseResolve(value) {
return new Promise(resolve => {
resolve(value);
});
}
myPromiseResolve(42).then(console.log);
// 42
myPromiseResolve(Promise.resolve("hello")).then(console.log);
// hello
Explanation
The native promise resolution procedure handles ordinary values, promises, thenables, self-resolution, and exceptions thrown while retrieving or invoking a thenable's then method.
The simplified implementation delegates those behaviors to the native Promise constructor's resolve function instead of reimplementing the entire algorithm.
Interview distinction: This is a wrapper around native promise resolution, not a replacement for the native static method. A full polyfill would also need to respect constructor identity and subclass behavior.
- Promise resolution adopts promises and thenables rather than treating them as ordinary nested values.
- Using the native constructor delegates the complex resolution procedure to the runtime.