欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

手写Promise

程序员文章站 2022-06-19 16:11:49
1. 无链式then// 先定义三个常量表示状态var PENDING = 'pending';var FULFILLED = 'fulfilled';var REJECTED = 'rejected';function MyPromise(fn) {this.status = PENDING; // 初始状态为pendingthis.value = null; // 初始化valuethis.err = null; // 初始化e...

1. 无链式then

// 先定义三个常量表示状态
var PENDING = 'pending';
var FULFILLED = 'fulfilled';
var REJECTED = 'rejected';

function MyPromise(fn) {
	this.status = PENDING;    // 初始状态为pending
	this.value = null;        // 初始化value
	this.err = null;       // 初始化err

	this.onFulfilledCallbacks = [] // Fulfilled回调数组
	this.onRejectedCallbacks = [] // Rejected回调数组

	// console.log(fn)

	// 存一下this,以便resolve和reject里面访问
	var that = this;
	// resolve方法参数是value
	function resolve(value) {
		if(that.status === PENDING) {
			that.status = FULFILLED;
			that.value = value;

			// 执行从PENDING到Fulfill的方法,如果MyPromise里没有异步任务,同步resolve,这里应该是空的
			that.onFulfilledCallbacks.forEach(cb => {
				cb(value)
			})
		}
	}

	// reject方法参数是err
	function reject(err) {
		if(that.status === PENDING) {
			that.status = REJECTED;
			that.err = err;

			// 执行从PENDING到Reject的方法
			that.onRejectedCallbacks.forEach(cb => {
				cb(err)
			})
		}
	}

	try {
		fn(resolve, reject);
		/*
		(function(resolve,reject)=>{
			setTimeout(()=>{
				resolve('hello')
			},2500)
		})(resolve,reject);
		*/
	} catch (error) {
 		reject(error);
	}
}

// two params of function then
MyPromise.prototype.then = function(onFulfilled,onReject){

	  //没有then链式调用
	  
	  // 状态改变 执行相应回调
	  // 能直接调用回调的两种情况,说明Promise构造时resolve没有异步执行  
	  if(this.status === FULFILLED) {
	    onFulfilled(this.value)
	  }
	  if(this.status === REJECTED) {
	    onRejected(this.err);
	  }

	  // 如果还是PENDING状态,说明Promise构造在异步执行,还没resolve/reject,所以先将回调保存下来
	  if(this.status === PENDING) {
	    this.onFulfilledCallbacks.push(onFulfilled);
	    this.onRejectedCallbacks.push(onReject);
	  } 
}


let p = new MyPromise((resolve,reject)=>{
	// resolve('hello')
	// 异步resolve
	setTimeout(()=>{
		resolve('hello')
	},1000)	
})


p.then(res=>{
	console.log(res);
})

本文地址:https://blog.csdn.net/qq_38765789/article/details/107388727

相关标签: JS