promise
前兩天遇到一個問題,讓多個接口全部都完成慈参,然后進(jìn)行某項操作呛牲,于是就在網(wǎng)上看了一個視頻,看了下基礎(chǔ)用法驮配,個人覺得講的不錯娘扩,就記錄下來了
promise分兩種階段, 三種狀態(tài)
一、 unsettled(未決階段)
1.unsettled階段只有一個狀態(tài)padding, padding是掛起狀態(tài), 表示等待
二壮锻、 settled(已決階段)有兩種狀態(tài)
1.resolved (成功狀態(tài))
resolve 是從未決推向已決的resolved狀態(tài)過程叫做resolve
resolved 成功后的處理稱之為thenable
2.rejected (失敗狀態(tài))
reject 從未決推向已決的rejected狀態(tài)過程叫做reject
rejected 錯誤后的處理稱之為catchable
看下圖很容易理解
promise.jpg
只要熟悉了流程琐旁,代碼上面就簡單多了
- 單獨使用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Promise</title>
<link rel="stylesheet" href="">
</head>
<body>
<script>
var pos = new Promise((resolve, reject) => { // 創(chuàng)建promise構(gòu)造函數(shù)
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function () { // 在發(fā)起請求的時候是未決階段,padding狀態(tài)
if (this.readyState === 4) {
if (this.status === 200) {
resolve(this.responseText); // 得到結(jié)果后 推向已決階段躯保,如果是成功推向 resolve狀態(tài)
} else {
reject(this); //如果是失敗旋膳,推向已決狀態(tài) reject
}
}
};
oReq.open("GET", "http://47.240.11.236:8080/json.json", true);
oReq.send();
});
pos.then(res => { // resolved 成功后的處理稱之為 thenable
console.log(res);
});
pos.catch(err => { // rejected 成功后的處理稱之為 catchable
console.log(err) // 錯誤處理
});
// then 和 catch 還有別的寫法,以下代碼等同于上面
// pos.then(res => {
// console.log(res);
// }, err => {
// console.log(res);
// });
</script>
</body>
</html>
Promise.all 使用
等待兩個接口同時完成后執(zhí)行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Promise.all</title>
<link rel="stylesheet" href="">
</head>
<body>
<script>
// 創(chuàng)建pos1
var pos1 = new Promise((resolve, reject) => { // 創(chuàng)建promise構(gòu)造函數(shù)
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function () { // 在發(fā)起請求的時候是未決階段途事,padding狀態(tài)
if (this.readyState === 4) {
if (this.status === 200) {
resolve(this.responseText); // 得到結(jié)果后 推向已決階段,如果是成功推向 resolve狀態(tài)
} else {
reject(this); //如果是失敗擅羞,推向已決狀態(tài) reject
}
}
};
oReq.open("GET", "http://47.240.11.236:8080/json.json", true);
oReq.send();
});
// 創(chuàng)建pos2
var pos2 = new Promise((resolve, reject) => { // 創(chuàng)建promise構(gòu)造函數(shù)
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function () { // 在發(fā)起請求的時候是未決階段尸变,padding狀態(tài)
if (this.readyState === 4) {
if (this.status === 200) {
resolve(this.responseText); // 得到結(jié)果后 推向已決階段,如果是成功推向 resolve狀態(tài)
} else {
reject(this); //如果是失敗减俏,推向已決狀態(tài) reject
}
}
};
oReq.open("GET", "http://47.240.11.236:8080/json.json", true);
oReq.send();
});
// Promise.all
Promise.all([pos1, pos2]).then(res => { // 等待 pos1 和 pos2 同時成功之后執(zhí)行
console.log(res[0]);
console.log(res[1]);
})
</script>
</body>
</html>