封装Promise构造函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanshaobo888/article/details/83825420
最新更新时间:2018年11月7日15:42:55

《猛戳-查看我的博客地图-总有你意想不到的惊喜》

本文内容:Promise对象封装

原生Promise对象的两个例子

//同步
new Promise((resolve,reject)=>{
	resolve('i am bruce');
}).then(param => console.log(param));//i am bruce

//异步
new Promise((resolve,reject)=>{
	setTimeout(resolve,1000,'i am async fun')
}).then(param => console.log(param));//i am async fun

只能处理同步的_Promise对象

function _Promise(){
	this.status = 'pending';
	this.msg = 'none';
	var self = this;
	var process = arguments[0];
	process(function(){
		self.status = 'resolve';
		self.msg = arguments[0];
	},function(){
		self.status = 'reject';
		self.msg = arguments[0];
	});
	//return this;
}
_Promise.prototype.then = function(){
	if(this.status == 'resolve'){
		arguments[0](this.msg);
	}else if((this.status == 'reject') && arguments[1]){
		arguments[1](this.msg);
	}
}
new _Promise(function(resolve,reject){resolve(123)}).then(function(msg){
	console.log(msg);
	console.log('success');
},function(msg){
	console.log(msg);
	console.log('fail!');
});
//123
//success

可以处理同步和异步的_Promise对象

function _Promise(){
	this.status = 'pending';
	this.statusSave = [];//存储then回调的两个函数体A和B,如:new _Promise().then(A,B)
	this.msg = 'none';
	var self = this;
	var executor = arguments[0];
	executor(function(){//resolve函数的实现
		var success = arguments[0];//resolve函数传入的参数
		self.status = 'resolved';
		self.msg = success;
		for (const { resolve } of self.statusSave) {
			resolve(success);
		}
	},function(){//reject函数的实现
		var err = arguments[0];//resolve函数传入的参数
		self.status = 'rejected';
		self.msg = err;
		for (const { reject } of self.statusSave) {
			reject(err);
		}
	});
	// return this;
}
_Promise.prototype.then = function(){
	var resolve = arguments[0];
	var reject = arguments[1];
	if(this.status == 'resolved'){
		resolve(this.msg);
	}else if(this.status == 'rejected'&& reject){
		reject(this.msg);
	}else{
		this.statusSave.push({resolve,reject});//
	}
}
//同步
new _Promise((resolve,reject) => {reject('async emit')}).then(function(msg){
	console.log(msg);
	console.log('success');
},function(msg){
	console.log(msg);
	console.log('fail!');
});
//async emit
//fail

//异步
new _Promise((resolve,reject) => {setTimeout(resolve,1000,'async emit')}).then(function(msg){
	console.log(msg);
	console.log('success');
},function(msg){
	console.log(msg);
	console.log('fail!');
});
//async emit
//success

感谢阅读,欢迎评论^-^

打赏我吧^-^

猜你喜欢

转载自blog.csdn.net/wanshaobo888/article/details/83825420