原生JS实现promise(只包括状态改变的代码)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<script>
		//用原生JS来实现promise类
		//promise有三个状态
		// pending,进行中
		// fulfilled,已完成(resolved)
		// rejected,已失败
		// promise的状态只能由pending=>fulfilled,或者由pending=>rejected,而且状态一旦改变就不会再变
		// 所以先定义三个常量来存储我们的状态值
		const PENDING = 'PENDING';
		const FULFILLED = 'FULFILLED';
		const REJECTED = 'REJECTED';
		// 定义一个函数来判断一个变量是不是函数
		// 原因是因为promise构造函数接受一个函数作为其参数,该函数的参数有两个,也是两个函数,用来改变promise对象的状态
		function isFun(fn){
			return typeof fn === 'function';
		}
		//简单实现
		class MyPromise{
			constructor(handle){
				if(!isFun(handle)){
					throw new Error('MyPromise must accept a function as a parameter');
				}
				//添加状态
				this._status = PENDING;
				//保存给resolve和reject函数传递过来的值
				this._value = undefined;
				//执行handle
				try{
					handle(this._resolve.bind(this),this._reject.bind(this));
				}catch(err){
					this._reject(err);
				}
			}
			//添加resolve时的函数
			_resolve(val){
				if(!this._status !== PENDING) return;
				this._status = FULFILLED;
				this._value = val;
			}
			//添加reject函数
			_reject(err){
				if(!this._status !== PENDING) return;
				this._status = REJECTED;
				this._value = err;
			}
		}
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/hahahahahahahaha__1/article/details/83117967