• 原生JavaScript实现一个简单的Promise构造函数示例


    下面demo示例,只支持实例的then和catch,代码如下:

    function PromiseDiffer(fn){
        var self = this;
        this.status = 'pendding';
        this.value = undefined;
        this.reason = null;
        function resolve(data) {
            self.status = 'fulfilled';
            self.successFn && self.successFn(data);
            self.value = data;
        }
        function reject(error) {
            self.status = 'rejected';
            self.errorFn && self.errorFn(error);
            self.reason = error;
        }
        
        fn && fn(resolve,reject);
        
        PromiseDiffer.prototype.then = function(onFulfilledCallback,onRejectedCallback) {
            if(this.status == 'fulfilled') {
                onFulfilledCallback && onFulfilledCallback(this.value);
            }
            if(this.status == 'rejected') {
                onRejectedCallback && onRejectedCallback(this.reason);
            }
            this.successFn = onFulfilledCallback;
            this.errorFn = onRejectedCallback;
            return this;
        }
        
        PromiseDiffer.prototype.catch = function(onRejected) {
            return this.then(null, onRejected);
        }
        
    }

    调用方式跟Promise一样,如下:

    var promise = new PromiseDiffer(function(resolve,reject){
        resolve('1');
    })
    promise.then(function(data){
        console.log(data)
    }).catch(function(err){
        
    })

    后续再添加完善其他方法。

  • 相关阅读:
    Sparc 10 with Simics
    Perl log 0906
    FPGA flow
    SV program与module的区别
    [基础]Verilog的$readmemx介绍
    [转载] 我对验证的一些理解
    我的书单
    boost 1_45_0 boost\cstdint.hpp 在 VS8下的 bug stdint.h 无法找到头文件
    Inside DllMain
    NoSQL数据库笔谈(转载)
  • 原文地址:https://www.cnblogs.com/moqiutao/p/14484261.html
Copyright © 2020-2023  润新知