Promise簡單實現

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise-polyfill</title>
</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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章