Skip to content

Instantly share code, notes, and snippets.

@Debbl
Last active March 4, 2022 13:03
Show Gist options
  • Save Debbl/03640522d516a993bbee7927ec3ac69b to your computer and use it in GitHub Desktop.
Save Debbl/03640522d516a993bbee7927ec3ac69b to your computer and use it in GitHub Desktop.
手写Promise
// https://promisesaplus.com/
// 状态定义
const PROMISE_STATUS_PENDING = 'pending';
const PROMISE_STATUS_FULFILLED = 'fulfilled';
const PROMISE_STATUS_REJECTED = 'rejected';
class MYPromise {
constructor(executor) {
this.status = PROMISE_STATUS_PENDING;
this.value = undefined;
this.reason = undefined;
const resolve = (value) => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_FULFILLED;
this.value = value;
console.log('resolve 被调用');
}
}
const reject = (reason) => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_REJECT;
this.reason = reason;
console.log('reject 被调用');
}
}
executor(resolve, reject)
}
}
const myPromise = new MYPromise((resolve, reject) => {
console.log('pending 状态');
resolve(111);
reject(222);
})
// https://promisesaplus.com/
// 状态定义
const PROMISE_STATUS_PENDING = 'pending';
const PROMISE_STATUS_FULFILLED = 'fulfilled';
const PROMISE_STATUS_REJECTED = 'rejected';
class MYPromise {
constructor(executor) {
this.status = PROMISE_STATUS_PENDING;
this.value = undefined;
this.reason = undefined;
const resolve = (value) => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_FULFILLED;
this.value = value;
console.log('resolve 被调用');
}
}
const reject = (reason) => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_REJECTED;
this.reason = reason;
console.log('reject 被调用');
}
}
executor(resolve, reject)
}
// then 方法
then(onFulfilled, onRejected) {
if (this.status === PROMISE_STATUS_FULFILLED) {
onFulfilled(this.value);
}
if (this.status === PROMISE_STATUS_REJECTED) {
onRejected(this.reason);
}
}
}
const myPromise = new MYPromise((resolve, reject) => {
console.log('pending 状态');
reject(222);
resolve(111);
})
myPromise.then((res) => {
console.log('res---', res);
}, (err) => {
console.log('err--', err);
})
// 多次调用 then
myPromise.then((res) => {
console.log('res---', res);
}, (err) => {
console.log('err--', err);
})
myPromise.then((res) => {
console.log('res---', res);
}, (err) => {
console.log('err--', err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment