前端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結構代碼
<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()
})
})();