简单实现版本
class Promise {
callbacks = [];
state = 'pending';
value = null;
constructor(fn) {
fn(this._resolve.bind(this))
}
then(onFulfilled) {
if (state === 'pending') {
this.callbacks.push(onFulfilled);
}
else {
onFulfilled(this.value);
}
return this;
}
_resolve(value) {
this.state = 'fulfilled';
this.value = value;
this.callbacks.forEach(fn => fn(value));
}
}
本文介绍了一个简单的Promise类实现,包括构造函数、then方法及状态管理。该实现支持将回调函数排队执行,并在状态变为已解决(fulfilled)时调用这些回调。
2099

被折叠的 条评论
为什么被折叠?



