前端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()
})
})();