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); } } } }; 二