爭搶特斯拉訂單:三星 SDI、LG 能源完成 4680 電芯研發
阿新 • • 發佈:2021-07-14
一、回撥函式
優點:簡單,方便,易用
缺點:易造成回撥函式地獄,回撥函式中巢狀多個回撥函式,因為多個非同步操作造成強耦合,程式碼亂做一團,無法管理。
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));
};
});
}