Promise实现

实现一个简单的promise

首先promise是一种异步解决方案,避免了开发中的回调地狱的问题,promise状态有三种,pending resolved,rejected 一旦状态改变将不可逆,也就是说状态只能由pending——resolved或者pending——rejected,下面来实现一个简单的promise函数

function PromiseMy(constructor){
	var self = this;
	this.state = 'pending';
	this.value = undefined;
	this.msg = undefined;
	function resolve (value){
		if(self.state === 'pending'){
			self.state = 'resolved';
			self.value = value;
        }
	}
   function reject(value){
		if(self.state === 'pending'){
			self.state = 'rejected';
			self.msg = msg;
        }
	}
	try{
		constructor(resolve,reject)
	}catch(e){
		reject(e)
	}
}
在原型上编写then方法
PromiseMy.prototype.then = function(onResolved,onRejected){
    var selef = this;
	if(selef.state == 'resolved'){
	   onResolved(selef.value)
    }else if(selef.state == 'resolved'){
       onRejected(selef.msg)
    }
}

你可能感兴趣的:(Promise实现)