自己实现promise功能
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
function Promise(executor) {
var _this = this
this.state = PENDING; //状态
this.value = undefined; //成功结果
this.reason = undefined; //失败原因
this.callback ={};
function resolve(value) {
if(_this.state === PENDING){
_this.state = FULFILLED
_this.value = value
if(_this.callback.onFulfilled){
_this.callback.onFulfilled(value)
}
}
}
function reject(reason) {
if(_this.state === PENDING){
_this.state = REJECTED
_this.reason = reason
if(_this.callback.onRejected){
_this.callback.onRejected(value)
}
}
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
Promise.prototype.then = function (onFulfilled, onRejected) {
if(this.state === FULFILLED){
onFulfilled(this.value)
}
if(this.state === REJECTED){
onRejected(this.reason)
}
if(this.state === PENDING){
this.callback ={onFulfilled,onRejected}
}
};
<script src="promise.js"></script>
<script>
let p=new Promise((resolve,reject)=>{
setTimeout(() => {
resolve('ok');
}, 100);
});
p.then(value=>{
console.log(value);
},reason=>{
console.log(reason);
});
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。