stay hungry stay foolish

实现Promise

class Promsie {
	constructor(excutor) {
		let that = this;
		this.PromiseResult = undefined;
		this.PromiseState = 'pending';
		this.callbacks = [];

		function resolve(data) {
			this.PromiseState = 'fullfilled';
			this.PromiseResult = data;
			this.callbacks.forEach(item => {
				item.onResolve(data);
			});
		}

		function reject() {
			this.PromiseState = 'rejected';
			this.PromiseResult = data;
			this.callbacks.forEach(item => {
				item.onReject(data);
			});
		}

		excutor(resolve, reject);
	}
	then(onResolve, onReject) {
		let that = this;

		if (typeof onResolve !== 'function') {
			onResolve = (data) => {
				return data;
			}
		}
		if (typeof onReject !== 'function') {
			onReject = (data) => {
				throw data;
			}
		}

		return new Promise(function(resove, reject) {
			function fun(callback) {
				try {
					let result = callback(that.PromiseResult);
					if (result instanceof Promsie) {
						result.then((r) => {
							resove(r);
						}, (r) => {
							reject(r);
						});
					} else {
						resove(result);
					}
				} catch (e) {
					reject(e);
				}
			}

			if (that.PromiseState === 'fullfilled') {
				fun(onResolve);
			}
			if (that.PromiseState === 'rejected') {
				fun(onReject);
			}
			if (that.PromiseResult === 'pending') {
				that.callbacks.push({
					onResolve: () => {
						fun(onResolve);
					},
					onReject: () => {
						fun(onReject);
					}
				});
			}
		});
	}
	catch(onReject) {
		return this.then(undefined, onReject);
	}
}