js处理异步的几种方式

  一、回调函数

优点:简单,方便,易用

缺点:易造成回调函数地狱,回调函数中嵌套多个回调函数,因为多个异步操作造成强耦合,代码乱做一团,无法管理。

var xhr1 = new XMLHttpRequest();
xhr1.open('GET''https://www.apiopen.top/weatherApi?city=广州');
xhr1.send();
xhr1.onreadystatechange = function() {
    if(this.readyState !== 4)  return;
    if(this.status === 200) {
        data1 = JSON.parse(this.response);
        var xhr2 = new XMLHttpRequest();
        xhr2.open('GET''https://www.apiopen.top/weatherApi?city=番禺');
        xhr2.send();
        xhr2.onreadystatechange = function() {
            if(this.readyState !== 4)  return;
            if(this.status === 200) {
                data2 = JSON.parse(this.response);
                console.log(data1, data2);
            }
        }
    }
};

  二、事件监听

优点:与回调函数相比,事件监听实现了代码的解耦,方便代码管理

缺点:使用不方便,每次都要手动地绑定和触发事件

var events=new Events();
events.addEvent('done',function(data1){
   var xhr=new XMLHttpRequest();
   xhr.open('GET','请求地址') ;
   xhr.send();
   xhr.onreadystatechange=function(){
          if(this.readyState!==4) return;
          if(this.status===200){
                 data1=JSON.parse(data1);
                var data2=JSON.parse(this.response);
                 console.log(data1,data2);
          }
    
})
var xhr=new XMLHttpRequest();
xhr.open('GET','请求地址‘’);
xhr.send();
xhr.onreadystatechange=function(){
    if(this.readyState!==4){
           return;
    }
     if(this.status===200){
            events.fireEvent('done,this.response)
     }
}   

  三、Promise

优点:将回调函数嵌套调用变成了链式调用,逻辑更强,执行顺序更清楚

缺点:代码冗余,异步操作都被包裹在Promise构造函数和then方法中,主题代码不明显,语义不清楚

new Promise(function(resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET''https://www.apiopen.top/weatherApi?city=广州');
    xhr.send();
    xhr.onreadystatechange = function() {
        if(this.readyState !== 4)  return;
        if(this.status === 200) return resolve(this.response);
        reject(this.statusText);
    };
}).then(function(value) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET''https://www.apiopen.top/weatherApi?city=番禺');
    xhr.send();
    xhr.onreadystatechange = function() {
        if(this.readyState !== 4)  return;
        if(this.status === 200) {
            const data1 = JSON.parse(value);
            const data2 = JSON.parse(this.response);
            console.log(data1, data2);
        }
    };
});

  四、async/await

async函数是generrator函数的语法糖,它相当于一个自带执行器的generator函数

async函数中的await接收一个Promise对象

优点:最简洁,最符合语义,最接近同步代码,最适合处理多个Promise异步操作

缺点:js语言自带的async执行器功能性可能没有co模块等执行器强

async function azc() {
    const data1 = await getJSON_PM('https://www.apiopen.top/weatherApi?city=广州');
    const data2 = await getJSON_PM('https://www.apiopen.top/weatherApi?city=番禺');
    console.log(data1, data2);
}
 
azc();
function getJSON_PM(url) {
    return new Promise((resolve, rejext) => {
        const xhr = new XMLHttpRequest();
         
        xhr.open('GET', url);
        xhr.responseType = "json";
        xhr.setRequestHeader("Accept""application/json");
        xhr.send();
         
        xhr.onreadystatechange = function() {
            if(this.readyState !== 4) return;
            if(this.status === 200) return resolve(this.response);
            reject(new Error(this.statusText));
        };
    });
}

转自:https://www.cnblogs.com/fms-3/p/11679271.html

原文地址:https://www.cnblogs.com/yonggang/p/15029825.html