头部前端代码轮必考。写得出说明你对异步状态机理解到规范级。
三态:pending/fulfilled/rejected,单向转移。
构造函数:接受executor (resolve, reject)=>{...},捕获回调。
.then(onFulfilled, onRejected):必须返回新Promise;链式靠执行handler然后用返回值resolve新Promise。
异步保证:handler始终异步执行(queueMicrotask或setTimeout),即使Promise已经resolve。
then里返回thenable:递归resolve(Promise/A+的2.3.3规则)。
三态pending/fulfilled/rejected单向转移。构造函数里收集pending时入队的回调,resolve/reject时依次触发。难点在.then:必须返回新Promise、handler必须异步跑(queueMicrotask)、必须采纳handler返回值的状态——包括返回的是另一个thenable(2.3.3递归)。最后这条是大多数手写实现通不过兼容性测试的地方。我背了约40行的版本:class MyPromise带state/value/handlers[],resolve/reject遍历handlers;then()`new MyPromise`,在executor里queueMicrotask跑当前handler,把返回值resolve给新Promise。达不到生产级但核心测试能过。
用queueMicrotask不用setTimeout——匹配规范的微任务语义。
别忘了finally():不管状态都跑、不观察值、透传。
即答侠有40行模板放手边——白板时不会卡壳。
为了链式。链上每一环必须独立可观察、可组合。返回同一个Promise会破坏fan-out。
Promise/A+里采纳thenable的规则——handler返回带.then的对象时新Promise要递归沿着它resolve。最难写对的一段。