ES 6 proimse &&iterator &&Generator函数 &&async

1.proimse   异步调用
function getData(){ let promise =new Promise((resolve,reject)); let xmlHttp =new XMLHttpRequest(); xmlHttp.onreadystatechange =function(){ if(xmlHttp.readyState===4){ if(xmlHttp.status==200){ resolve(xmlHttp.response) }else{ reject('数据没有内容') } } }; xmlHttp.open(tyoe="GET",url,true) xmlHttp.send() } getData(GET,url).then((data)=> { console,log(data.url1) let url1 =data.url1 return getData(GET,url1);//返出promise对象(多次调用) },(error)=>{ console,log(error) }) .then(()=>{ //链式调用, }).catch(()=>{ }) getData(POST,url).then((data)=> { console,log(data) },(error)=>{ console,log(error) })

  2.iterator 接口与 Generator 函数

Iterator 接口与 Generator 函数

Symbol.iterator方法的最简单实现,还是使用下一章要介绍的 Generator 函数。

let myIterable = {
  [Symbol.iterator]: function* () {
    yield 1;
    yield 2;
    yield 3;
  }
}
[...myIterable] // [1, 2, 3]

// 或者采用下面的简洁写法

let obj = {
  * [Symbol.iterator]() {
    yield 'hello';
    yield 'world';
  }
};

for (let x of obj) {
  console.log(x);
}
// "hello"
// "world"

 3.Generator 异步调用

<script src='../jquery.min.js'></script>
<script >
 function getData(url){
     $.get(url,function(data){
        console.log(data)
        let url ='http://127.0.0.1:3000' +data.urlId
        SX.next('');//新闻详情的请求
     })
 }
 function* sendxml(){
     //新闻列表的请求
     let url = yield getData('http://127.0.0.1:3000/newslist')
     //新闻详情的请求
     yield getData(url)
 }
let SX =sendxml();
SX.next(); //新闻列表的请求


</script>

 7.async

async function getData(url){
    return new Promise((resolve,reject))
    $.ajax({
        method:'GET',
        url,
        success:data =>{
            resolve(data)
        },
        error:(error) =>reject() 
    })

}

async function SendXM(){
    let result = await  getData('http://127.0.0.1:3000/newslist')
    await getData('http://127.0.0.1:3000' + result.urlId)
}

SendXM()
 

  

原文地址:https://www.cnblogs.com/tsgxj/p/10482670.html