1 Star 0 Fork 0

QSQ1989/测试demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
5、promise简单实现.js 2.51 KB
一键复制 编辑 原始数据 按行查看 历史
QSQ1989 提交于 2018-09-10 09:26 . 简单demo
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)
})
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wenwenqiangqiang/test_demo.git
git@gitee.com:wenwenqiangqiang/test_demo.git
wenwenqiangqiang
test_demo
测试demo
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385