好程式設計師web前端教程分享前端javascript練習題之promise

好程式設計師IT發表於2019-11-28

好程式設計師web 前端教程分享 前端javascript 練習題 promise

promise-ajax的封裝

function ajax(url){//建立promise物件

   var promise = new Promise(function(resolve,reject){

   //建立ajax物件

         if(window.XMLHttpRequest){

            var xhr = new XMLHttpRequest();

         }else{

            var xhr = new ActiveXObject("Microsoft.XMLHTTP");

         }

         

         xhr.open("get",url,true);

         xhr.send();

         

         xhr.onreadystatechange = function(){

            if(xhr.readyState == 4){

               if(xhr.status == 200){

                  var data = xhr.responseText;

                  resolve(data);

               }else{

                  reject();

               }

            }

         }

   

   })

   return promise;  //返回promise物件}

紅綠燈

html結構程式碼

<ul id="traffic" class="">

    <li id="green"></li>

    <li id="yellow"></li>

    <li id="red"></li></ul>

css樣式程式碼:

ul {

    position: absolute;

    width: 200px;

    height: 200px;

    top: 50%;

    left: 50%;

    transform: translate(-50%, -50%);

    }

    /*畫3個圓代表紅綠燈*/

 

    ul>li {

    width: 40px;

    height: 40px;

    border-radius: 50%;

    opacity: 0.2;

    display: inline-block;

    }

    /*執行時改變透明度*/

 

    ul.red>#red,

    ul.green>#green,

    ul.yellow>#yellow {

    opacity: 1.0;

    }

    /*紅綠燈的三個顏色*/

 

    #red {

    background: red;

    }

 

    #yellow {

    background: yellow;

    }

 

    #green {

    background: green;}

js實現程式碼:

function timeout(timer) {

     return function() {

          return new Promise(function(resolve, reject) {

                setTimeout(resolve, timer)

                     })

                 }

             }

         var green = timeout(1000);

         var yellow = timeout(1000);

         var red = timeout(1000);

         var traffic = document.getElementById("traffic");

        

         (function restart() {

             'use strict' //嚴格模式

             traffic.className = 'green';

             green().then(function() {

                     traffic.className = 'yellow';

                     return yellow();

                 })

                 .then(function() {

                     traffic.className = 'red';

                     return red();

                 }).then(function() {

                     restart()

                 })

         })();


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69913892/viewspace-2666112/,如需轉載,請註明出處,否則將追究法律責任。

相關文章