手写实现es6语法primose(简易版)
大致代码如下
/**
* @description Promise
* @author rory
*/
((window)=>{
const STATUS = {
PENDING:'Pending',
RESOVLE:'Resolve',
REJECTS:'rejects',
}
window.PPromise = class PPromise{
status = {
value:STATUS['PENDING'],
result:null,
};
_resolveFn = null;
_rejectsFn = null;
constructor(props) {
props(
this.resolve.bind(this),
this.rejects.bind(this),
);
}
resolve( e ) {
this.status.value = STATUS['RESOVLE'];
this.status.result = e;
this.then(this._resolveFn);
return this;
}
rejects( e ) {
this.status.value = STATUS['REJECTS'];
this.status.result = e;
this.catch(this._resolveFn);
return this;
}
then( _resolveFn ){
this._resolveFn = _resolveFn;
this.status.value === STATUS['RESOVLE']?_resolveFn(this.status.result):void(0);
return this;
}
catch( _rejectsFn ){
this._rejectsFn = _rejectsFn;
this.status.value === STATUS['REJECTS']?_rejectsFn(this.status.result):void(0);
return this;
}
}
})(window);
使用
function awaitPromise(){
return new PPromise( ( resolve, rejects) => {
setTimeout( () => {
if(1===1){
resolve('ok');
}else{
rejects('error');
}
},1000)
});
}
awaitPromise().then( res => {
console.log(res);
}).catch( err => {
console.log(err);
})