手写一个简单Promise

	function _Promise(fn) {
			var that = this;
			this.status = 'pending';
			this.value = '';
			this.error = '';
			this.onSuccess = [];
			this.onReject = [];

			function resolve(value) {
				if (that.status == 'pending') {
					that.value = value;
					that.status = 'success';
					that.onSuccess.forEach(fu => fu(value))
				}
			}

			function reject(value) {
				if (that.status == 'pending') {
					that.error = value;
					that.status = 'reject';
					that.onReject.forEach(fu => fu(value))
				}
			}
			try {

				fn(resolve, reject)
			} catch (e) {

				resolve(e)
			}


		}


		_Promise.prototype.then = function(onResolve, onReject) {
	
			if (this.status === 'success') {
	
				typeof onResolve === 'function' ? onResolve(this.value) : ''

			} else if (this.status === 'reject') {
				typeof onReject === 'function' ? onReject(this.error) : ''
			} else if (this.status === 'pending') {

				typeof onResolve === 'function' ? this.onSuccess.push(onResolve) : ''
				typeof onReject === 'function' ? this.onReject.push(onReject) : ''
			}

		}

调用测试

		new _Promise((resolve, reject) => {
             setTimeout(()=>{
				 resolve('success')
			 },500)
		}).then(res => {
			        console.log(res)
		}, err => {
              console.log(err)
		})

结果:

猜你喜欢

转载自blog.csdn.net/sd1sd2/article/details/123129508