promise
2018-06-08 本文已影响0人
我竟无言以对_1202
<div id="box"></div>
<script>
let url01 = "http://api.unclealan.cn:4100/movie/top";
let url02 = "http://api.unclealan.cn:4100/movie/subject/";
let url03 = "http://api.unclealan.cn:4100/movie/celebrity/";
// 获取电影排行榜信息
function getTopInfo(){
return new Promise(function(resolve,reject){
let xhr = new XMLHttpRequest();
xhr.onload = function(){
resolve(JSON.parse(xhr.responseText));
}
xhr.onerror = function(){
reject("请求电影排行榜失败");
}
xhr.open("GET",url01);
xhr.send();
})
}
// 获取电影详细信息
function getMovieInfo(id){
return new Promise(function(resolve,reject){
let xhr = new XMLHttpRequest();
xhr.onload = function(){
resolve(JSON.parse(xhr.responseText));
}
xhr.onerror = function(){
reject("请求电影详细信息失败");
}
xhr.open("GET",url02+id);
xhr.send();
})
}
// 获取导演信息
function getDirectorInfo(id){
return new Promise(function(resolve,reject){
let xhr = new XMLHttpRequest();
xhr.onload = function(){
resolve(JSON.parse(xhr.responseText));
}
xhr.onerror = function(){
reject("请求导演信息失败");
}
xhr.open("GET",url03+id);
xhr.send();
})
}
let message = "排行榜第一的电影是:";
getTopInfo().then(function(res){
message += res.subjects[0].title + "<br/>"
return getMovieInfo(res.subjects[0].id);
}).then(function(res){
message += "导演是:" + res.directors[0].name + "<br/>"
return getDirectorInfo(res.directors[0].id);
}).then(function(res){
message += "导演的故乡在:" + res.born_place;
document.querySelector("#box").innerHTML = message;
},function(msg){
console.log(msg);
})
</script>
<div id="box"></div>
<script>
let url01 = "http://api.unclealan.cn:4100/movie/top";
let url02 = "http://api.unclealan.cn:4100/movie/subject/";
let url03 = "http://api.unclealan.cn:4100/movie/celebrity/";
function getInfo(url,errMes,id=0){
if(id!==0){
url += id;
}
return new Promise(function(resolve,reject){
let xhr = new XMLHttpRequest();
xhr.onload = function(){
resolve(JSON.parse(xhr.responseText));
}
xhr.onerror = function(){
reject(errMsg);
}
xhr.open("GET",url);
xhr.send();
})
}
let message = "排行榜第一的电影是:";
getInfo(url01,"获取电影排行榜失败").then(function(res){
message += res.subjects[0].title;
return getInfo(url02,"获取电影详情失败",res.subjects[0].id);
}).then(function(res){
message += "导演是:"+res.directors[0].name;
return getInfo(url03,"获取导演失败",res.directors[0].id);
}).then(function(res){
message += "导演的故乡:"+res.born_place;
document.querySelector("#box").innerHTML = message;
},function(msg){
console.log(msg);
})
</script>