Promise简单实现

来源:互联网 发布:2017科幻电影推荐知乎 编辑:程序博客网 时间:2024/06/05 23:01
<!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>
原创粉丝点击