美文网首页
Promise的简单实现

Promise的简单实现

作者: 前端人 | 来源:发表于2019-10-08 10:25 被阅读0次

es6版本的

 class Spromise{
/**
 * Creates an instance of Spromise.
 * @param {any} doFn function
 * 
 * @memberOf Spromise
 */
constructor(doFn){

    /**内部状态 */
    this.statue='pending';
    /**异步执行成功后要执行的函数 */
    this._thenFn=null;
    /**异步执行失败后要执行的函数 */
    this._errFn=null;


    if(!( doFn instanceof Function))
        return this;
    try{

        /**这里的 this._success 函数一定要bind绑定作用域为本this */
        doFn(this._success.bind(this),this._fail.bind(this));

    }
    catch(err){
        this.errFn(err);
    }
 
    return this;
}
/**
 * 内部成功的函数
 * 
 * @param {any} obj 
 * 
 * @memberOf Spromise
 */
_success(obj){
   
    this.statue='success';
    this._thenFn(obj);
}  

/**
 * 内部执行失败的函数
 * 
 * @param {any} obj 
 * 
 * @memberOf Spromise
 */
_fail(obj){
    this.statue='fail';
    this._errFn(obj);
}

/**
 * 注册执行失败的函数
 * 
 * @param {any} fn 
 * @returns 
 * 
 * @memberOf Spromise
 */
catch(fn){
    if(!( fn instanceof Function))
        return;
    this._errFn=fn;
    return this;
}

/**
 * 注册执行成功的函数
 * 
 * @param {any} fn 
 * @returns 
 * 
 * @memberOf Spromise
 */
then(fn){
    if(!( fn instanceof Function))
        return;
    this._thenFn=fn;  
    return this;
   }
}

export default Spromise;

es5版本 promise

function Tpromise(doFn){


/**内部状态 */
this.statue='pending';
/**异步执行成功后要执行的函数 */
this._thenFn=null;
/**异步执行失败后要执行的函数 */
this._errFn=null;


if(!( doFn instanceof Function))
    return this;
try{

    /**这里的 this._success 函数一定要bind绑定作用域为本this */
    doFn(this._success.bind(this),this._fail.bind(this));

}
catch(err){
    this.errFn(err);
}
 
return this;

  }

 /**注册成功执行的回调函数 */
Tpromise.prototype.then=function(fn){
   if(!( fn instanceof Function))
      return;
  this._thenFn=fn;  
return this;  
};

   /**
 * 内部成功的函数
 * 
 * @param {any} obj 
 * 
 * @memberOf Spromise
 */
Tpromise.prototype._success=function(obj){
   
this.statue='success';
this._thenFn(obj);
};  

 /**
 * 内部执行失败的函数
 * 
 * @param {any} obj 
 * 
 * @memberOf Spromise
 */
  Tpromise.prototype. _fail=function(obj){
this.statue='fail';
this._errFn(obj);
 };

  /**
 * 注册执行失败的函数
 * 
 * @param {any} fn 
 * @returns 
 * 
 * @memberOf Spromise
 */
 Tpromise.prototype.catch=function(fn){
if(!( fn instanceof Function))
    return;
this._errFn=fn;
return this;
 };

友情提醒

promise还有很多特征 这里的实现还缺很多特征

相关文章

网友评论

      本文标题:Promise的简单实现

      本文链接:https://www.haomeiwen.com/subject/lttbpctx.html