手写一个Promise


<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Documenttitle>
head>
<body>
	<script>
		function Promisetest(executor){
      
			let that = this;
			this.value = null;
			this.reason = null;
			this.status = 'pending';
			this.onResolvedCallbacks = [];
			this.onRejectedCallbacks = [];

			function resolve(value){
      
				if(that.status === 'pending'){
      
				that.value = value;
					that.status = 'resolved';//成功
					that.onResolvedCallbacks.forEach(fn=>{
      
						fn()
					})
				} 
			}

			function reject(reason){
      
				if(that.status==='pending'){
      
					that.reason = reason;
					that.status = 'rejected'
					that.onRejectCallbacks.forEach(fn=>{
      
						fn()
					})
				}
			}

			executor(resolve,reject);
		}


		Promisetest.prototype.then = function(onFulfilled,onRejected){
      
			let that = this;
			if(this.status === 'pending'){
      
				this.onResolvedCallbacks.push(function(){
      
					onFulfilled(that.value)
				})
				this.onRejectedCallbacks.push(function(){
      
					onRejected(that.reason)
				})
			}


			if(this.status === 'resolved'){
      
				onFulfilled(this.value)
			}

			if(this.status === 'rejected'){
      
				onRejected(this.reason)
			}
		}

		// 使用
		function test(){
      
			return new Promisetest((resolve,reject)=>{
      
				setTimeout(()=>{
      
					return resolve(33)
				},1000)
			})
		}

		test().then(val=>{
      
			console.log(val+67)
		})
	script>
body>
html>

你可能感兴趣的:(手写一个Promise)