代码拉取完成,页面将自动刷新
class MyPromise {
constructor(fn) {
if (typeof fn !== 'function') {
throw new TypeError(`MyPromise fn ${fn} is not a function`)
}
this.state = 'pending';
this.value = void 0;
fn(this.resolve.bind(this), this.reject.bind(this))
}
resolve(value) {
if (this.state !== 'pending') return;
this.state = 'fulfilled';
this.value = value
}
reject(reason) {
if (this.state !== 'pending') return;
this.state = 'rejected';
this.value = reason
}
then(fulfilled, rejected) {
if (typeof fulfilled !== 'function' && typeof rejected !== 'function') {
return this;
}
if (typeof fulfilled !== 'function' && this.state === 'fulfilled' ||
typeof rejected !== 'function' && this.state === 'rejected') {
return this;
}
return new MyPromise((resolve, reject) => {
if (fulfilled && typeof fulfilled === 'function' && this.state === 'fulfilled') {
let result = fulfilled(this.value);
if (result && typeof result.then === 'function') {
return result.then(resolve, reject)
} else {
resolve(result)
}
}
if (rejected && typeof rejected === 'function' && this.state === 'rejected') {
let result = rejected(this.value);
if (result && typeof result.then === 'function') {
return result.then(resolve, reject)
} else {
resolve(result)
}
}
})
}
catch(rejected) {
return this.then(null, rejected)
}
}
new MyPromise((resolve, reject) => {
console.log(1);
//reject(2)
resolve(2)
console.log(3)
setTimeout(() => {
console.log(4)
}, 0)
}).then(res => {
console.log(res)
return new MyPromise((resolve, reject) => {
resolve(5)
}).then(res => {
return res
})
}).then(res => {
console.log(res)
}).catch(e => {
console.log('e', e)
})
/**
* 原生实现
*/
new Promise((resolve, reject) => {
console.log(1);
//reject(2)
resolve(2)
console.log(3)
setTimeout(() => {
console.log(4)
}, 0)
}).then(res => {
console.log(res)
return new Promise((resolve, reject) => {
resolve(5)
}).then(res => {
return res
})
}).then(res => {
console.log(res)
}).catch(e => {
console.log('e', e)
})
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。