fetch API处置惩罚异步嵌套题目
我们昨天进修了async和await,晓得他是为了处置惩罚浏览器异步猎取的的!然则我们用fetch api的话要领会越发的简朴
async和await处置惩罚异步嵌套
function ajax(url){
return new Promise(function(reslove,reject){
let xmlHttp=new XMLHttpRequest();
xmlHttp.open("get",url,true);
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
let data=JSON.parse(xmlHttp.responseText);
reslove(data);
}
}
xmlHttp.send(null);
})
}
let uldom=document.getElementById("students");
let url="http://192.168.0.57:8000/students.json";
async function main(){
let data=await ajax(url);
let students=data;
let html="";
for(let i=0,l=students.length;i<l;i++){
let name=students[i].name;
let age=students[i].age;
html+=`
<li>姓名${name},岁数${age}</li>
`
}
uldom.innerHTML=html;
}
main();
我们须要建立Promise函数来举行操纵,假如我们用fetch处置惩罚的话,会越发的轻易!
let uldom=document.getElementById("students");
let url="http://192.168.0.57:8000/students.json";
function main(){
fetch(url).then(respone=>{
return respone.json();
}).then(data=>{
let students=data;
let html="";
for(let i=0,l=students.length;i<l;i++){
let name=students[i].name;
let age=students[i].age;
html+=`
<li>姓名${name},岁数${age}</li>
`
}
uldom.innerHTML=html;
});
}
main();
不必建立Promise,直接挪用then()是否是比上边越发的简朴!
async、await连系fetch处置惩罚异步
let uldom=document.getElementById("students");
let url="http://192.168.0.57:8000/students.json";
async function main(){
let respone = await fetch(url);
let student = await respone.json();
let html="";
for (let i=0,l=students.length;i<l;i++){
let name=students[i].name;
let age=students[i].age;
html+=`
<li>姓名${name},岁数${age}</li>
`
}
uldom.innerHTML=html;
}
main()
觉得是否是很简朴!比上一种要领越发的简朴。