1. 程式人生 > 資訊 >爭搶特斯拉訂單:三星 SDI、LG 能源完成 4680 電芯研發

爭搶特斯拉訂單:三星 SDI、LG 能源完成 4680 電芯研發

一、回撥函式

優點:簡單,方便,易用

缺點:易造成回撥函式地獄,回撥函式中巢狀多個回撥函式,因為多個非同步操作造成強耦合,程式碼亂做一團,無法管理。

varxhr1 =newXMLHttpRequest(); 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);
varxhr2 =newXMLHttpRequest(); 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); } } } };

  二、事件監聽

優點:與回撥函式相比,事件監聽實現了程式碼的解耦,方便程式碼管理

缺點:使用不方便,每次都要手動地繫結和觸發事件

varevents=newEvents(); events.addEvent('done',function(data1){ varxhr=newXMLHttpRequest(); xhr.open('GET','請求地址') ; xhr.send(); xhr.onreadystatechange=function(){ if(this.readyState!==4)return; if(this.status===200){ data1=JSON.parse(data1); vardata2=JSON.parse(this.response);
console.log(data1,data2); } } }) varxhr=newXMLHttpRequest(); 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方法中,主題程式碼不明顯,語義不清楚

newPromise(function(resolve, reject) { const xhr =newXMLHttpRequest(); xhr.open('GET','https://www.apiopen.top/weatherApi?city=廣州'); xhr.send(); xhr.onreadystatechange =function() { if(this.readyState !== 4)return; if(this.status === 200)returnresolve(this.response); reject(this.statusText); }; }).then(function(value) { const xhr =newXMLHttpRequest(); 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模組等執行器強

asyncfunctionazc() { 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(); functiongetJSON_PM(url) { returnnewPromise((resolve, rejext) => { const xhr =newXMLHttpRequest(); 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)returnresolve(this.response); reject(newError(this.statusText)); }; }); }

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