Bootstrap

手写promise简版

手写promise简版

1.首先我们写上他的三个主要架构,即resolve,reject,then。和必要一些变量
// 三种状态
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

function Promise(executor) {
    this.state = PENDING; //状态
    this.value = undefined; //成功结果
    this.reason = undefined; //失败原因
    
    function resolve(value) {}
    function reject(reason) {}
}

Promise.prototype.then = function (onFulfilled, onRejected) {
};
2.把resolve,reject,then方法写上
        const PENDING = 'pending'
		const FULFILLED = 'fulfilled'
		const REJECTED = 'rejected'

		function Mypromise(executor) {
			var _this = this
			this.state = PENDING; //状态
			this.value = undefined; //成功结果
			this.reason = undefined; //失败原因
			function resolved(value) {
				if (_this.state === 'pending') {
					_this.value = value
					_this.state = FULFILLED
				}
			}

			function rejected(reason) {
				if (_this.state === 'pending') {
					_this.reason = reason
					_this.state = REJECTED
				}
			}

			executor(resolved, rejected)
		}

		Mypromise.prototype.then = function(onFulfilled, onRejected) {
			if (this.state === 'fulfilled') {
				onFulfilled(this.value)
			}
			if (this.state === 'rejected') {
				onFulfilled(this.reason)
			}
		};
		new Mypromise((resolve, reject) => {
		    if(xxxx){
		       resolve('我是resolve')
		    }else{
		       reject('我是reject')
		    }
		}).then(res => {
			console.log('res', res)
		})
3.过程解析:

3.1首先executor是个回调函数,他本来是executor=function(resolve, reject){},需要注意的就是resolve和reject并不是用来传值的,而是被调用时用来接收值的,即executor()回调的时候,把resolved方法赋值给resolve,把rejected赋值给reject,从而,如果调用resolve()则会把state状态改为FULFILLED,如果是reject()方法,则状态改为REJECTED,然后进入then函数。

;