Promise 단순화


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise-polyfilltitle>
head>
<body>
    <script type="text/javascript"> //Promise-polyfill function Promise(fn) { var state = 'pending'; var doneList = []; this.then = function(done, fail) { switch(state) { case 'pending': doneList.push(done); return this; break; case 'fulfilled': done(); return this; break; case 'rejected': fail(); return this; break; } // ,  doneList.push(done); //  return this; } function resolve(newValue) { state = 'fulfilled'; //  var value = newValue; // , donelist  setTimeout(function(){ var value = newValue; for (var i = 0; i < doneList.length; i++){ var temp = doneList[i](value); if(temp instanceof Promise){ var newP = temp; for(i++; i < doneList.length; i++){ newP.then(doneList[i],failList[i]); } }else{ value = temp; } } }, 0); // doneList.forEach(function(fulfill) { // value = fulfill(value); // }); } function reject(newValue) { state = "rejected"; setTimeout(function() { var value = newValue; var tempRe = failList[0](value); // reject promise, fail , done fail promise  if(tempRe instanceof Promise) { var newP = tempRe; for(i = 1;i < doneList.length; i++) { newP.then(doneList[i],failList[i]); } }else { // promise, fail , doneList value = tempRe; doneList.shift(); failList.shift(); resolve(value); } }, 0); } fn(resolve, reject); } var promise = new Promise(function(resolve) { // console.log('hehehe') resolve(); }); promise.then(function() { console.log('resolve') }); script>
body>
html>

좋은 웹페이지 즐겨찾기