Promise의 원리 실현--필기 정리

12804 단어 ES6프런트 엔드

<html>
	<head>
		<meta charset="utf-8" />
		<title>title>
	head>
	<body>
		<script type="text/javascript">
			var fn = function(resolve, reject) {
				setTimeout(function() {
					if (true) {
						resolve(' ')
					} else {
						reject(' ')
					}
				}, 3000)
			}

			class AhfPromise {
				constructor(fn) {
					// successList 
					this.successList = [];
					// failList 
					this.failList = [];
					//pending,fullfilled,rejected
					this.state = 'pending';
					// ,( )
					fn(this.resolveFn.bind(this), this.rejectFn.bind(this))
				}
				then(successfn, failFn) {
					if (typeof successfn == "function") {
						this.successList.push(successfn)
					}
					if (typeof failFn == "function") {
						this.failList.push(failFn)
					}
				}
				catch (failFn) {
					if (typeof failFn == "function") {
						this.failList.push(failFn)
					}
				}
				resolveFn(res) {
					this.state = 'fullfilled'
					this.successList.forEach(function(item, index) {
						// 
						item(res);
					})
				}
				rejectFn(res) {
					this.state = 'rejected'
					// 
					this.failList.forEach(function(item, index) {
						item(res);
					})
					throw Error(" ")
				}
			}
			
			
			var p1 = new AhfPromise(fn)
			p1.then(res => {
				console.log(' ');
				console.log(res)
			})
			p1.then(() => {

			})
			p1.catch(res => {
				console.log(' , ');
				console.log(res)
			})
		script>
	body>
html>

좋은 웹페이지 즐겨찾기