4

fetch

  • async和await解决异步嵌套问题:

 function ajax(url){
        return new Promise(function(resolve,refused){
                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);
                        resolve(data);
                       }
                   }
                xmlHttp.send(null);
        });
    }

    let uldom=document.getElementById("students");
    let url="http://localhost:3000/student.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();
  • fetch解决异步嵌套问题:

let url="http://localhost:3000/student.json";
    let uldom=document.getElementById("students");
    async function main(){
        let respone = await fetch(url);
        let students = 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();

这两段代码比起来,是不是下面的要比上面的简单的多得多,像我这不爱敲代码的肯定选择下面的,哈哈!


songze
211 声望13 粉丝

该来的总会来,该走的不挽留!