原生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){ })
后续再添加完善其他方法。