promise
- 主要解決異步深層嵌套的問題
- promise 提供了簡潔的API 使得異步操作更加容易
<script type="text/javascript">
/*
1. Promise基本使用
我們使用new來構(gòu)建一個Promise Promise的構(gòu)造函數(shù)接收一個參數(shù),是函數(shù),并且傳入兩個參數(shù): resolve,reject, 分別表示異步操作執(zhí)行成功后的回調(diào)函數(shù)和異步操作執(zhí)行失敗后的回調(diào)函數(shù)
*/
var p = new Promise(function(resolve, reject){
//2. 這里用于實現(xiàn)異步任務(wù) setTimeout
setTimeout(function(){
var flag = false;
if(flag) {
//3. 正常情況
resolve('hello');
}else{
//4. 異常情況
reject('出錯了');
}
}, 100);
});
// 5 Promise實例生成以后,可以用then方法指定resolved狀態(tài)和reject狀態(tài)的回調(diào)函數(shù)
// 在then方法中,你也可以直接return數(shù)據(jù)而不是Promise對象,在后面的then中就可以接收到數(shù)據(jù)了
p.then(function(data){
console.log(data)
},function(info){
console.log(info)
});
</script>
基于Promise發(fā)送Ajax請求
<script type="text/javascript">
/*
基于Promise發(fā)送Ajax請求
*/
function queryData(url) {
# 1.1 創(chuàng)建一個Promise實例
var p = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
# 1.2 處理正常的情況
resolve(xhr.responseText);
}else{
# 1.3 處理異常情況
reject('服務(wù)器錯誤');
}
};
xhr.open('get', url);
xhr.send(null);
});
return p;
}
# 注意: 這里需要開啟一個服務(wù)
# 在then方法中,你也可以直接return數(shù)據(jù)而不是Promise對象,在后面的then中就可以接收到數(shù)據(jù)了
queryData('http://localhost:3000/data')
.then(function(data){
console.log(data)
# 1.4 想要繼續(xù)鏈?zhǔn)骄幊滔氯?需要 return
return queryData('http://localhost:3000/data1');
})
.then(function(data){
console.log(data);
return queryData('http://localhost:3000/data2');
})
.then(function(data){
console.log(data)
});
</script>
then參數(shù)中的函數(shù)返回值
<script type="text/javascript">
/*
then參數(shù)中的函數(shù)返回值
*/
function queryData(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
// 處理正常的情況
resolve(xhr.responseText);
}else{
// 處理異常情況
reject('服務(wù)器錯誤');
}
};
xhr.open('get', url);
xhr.send(null);
});
}
queryData('http://localhost:3000/data')
.then(function(data){
return queryData('http://localhost:3000/data1');
})
.then(function(data){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(123);
},1000)
});
})
.then(function(data){
return 'hello';
})
.then(function(data){
console.log(data)
})
</script>
Promise常用API-實例方法
function foo() {
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(123);
//reject('error');
}, 100);
})
}
// foo()
// .then(function(data){
// console.log(data)
// })
// .catch(function(data){
// console.log(data)
// })
// .finally(function(){
// console.log('finished')
// });
// --------------------------
// 兩種寫法是等效的
foo()
.then(function(data){
console.log(data)
},function(data){
console.log(data)
})
.finally(function(){
console.log('finished')
});

image.png
Promise常用API-對象方法
function queryData(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
// 處理正常的情況
resolve(xhr.responseText);
}else{
// 處理異常情況
reject('服務(wù)器錯誤');
}
};
xhr.open('get', url);
xhr.send(null);
});
}
.all()
-
Promise.all方法接受一個數(shù)組作參數(shù),數(shù)組中的對象(p1、p2、p3)均為promise實例(如果不是一個promise,該項會被用Promise.resolve轉(zhuǎn)換為一個promise)。它的狀態(tài)由這三個promise實例決定
Promise.all([p1,p2,p3]).then(function(result){
console.log(result)
})

請求來的數(shù)據(jù).png

image.png
.race()
-
Promise.race方法同樣接受一個數(shù)組作參數(shù)。當(dāng)p1, p2, p3中有一個實例的狀態(tài)發(fā)生改變(變?yōu)?code>fulfilled或rejected),p的狀態(tài)就跟著改變。并把第一個改變狀態(tài)的promise的返回值,傳給p的回調(diào)函數(shù)
.png
雖然返回的是第一個結(jié)果,但是所有數(shù)據(jù)都請求成功了.png
fetch
- Fetch API是新的ajax解決方案 Fetch會返回Promise
- fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest對象。
- fetch(url, options).then()
Fetch API 基本用法
<script type="text/javascript">
/*
Fetch API 基本用法
fetch(url).then()
第一個參數(shù)請求的路徑 Fetch會返回Promise 所以我們可以使用then 拿到請求成功的結(jié)果
*/
fetch('http://localhost:3000/fdata').then(function(data){
// text()方法屬于fetchAPI的一部分,它返回一個Promise實例對象,用于獲取后臺返回的數(shù)據(jù)
return data.text();
}).then(function(data){
// 在這個then里面我們能拿到最終的數(shù)據(jù)
console.log(data);
})
</script>
fetch API 中的 HTTP 請求
- fetch(url, options).then()
- HTTP協(xié)議,它給我們提供了很多的方法,如POST,GET,DELETE,UPDATE,PATCH和PUT
- 默認的是 GET 請求
- 需要在 options 對象中 指定對應(yīng)的 method method:請求使用的方法
- post 和 普通 請求的時候 需要在options 中 設(shè)置 請求頭 headers 和 body
<script type="text/javascript">
/*
Fetch API 調(diào)用接口傳遞參數(shù)
*/
#1.1 GET參數(shù)傳遞 - 傳統(tǒng)URL 通過url ? 的形式傳參
fetch('http://localhost:3000/books?id=123', {
# get 請求可以省略不寫 默認的是GET
method: 'get'
})
.then(function(data) {
# 它返回一個Promise實例對象,用于獲取后臺返回的數(shù)據(jù)
return data.text();
}).then(function(data) {
# 在這個then里面我們能拿到最終的數(shù)據(jù)
console.log(data)
});
#1.2 GET參數(shù)傳遞 restful形式的URL 通過/ 的形式傳遞參數(shù) 即 id = 456 和id后臺的配置有關(guān)
fetch('http://localhost:3000/books/456', {
# get 請求可以省略不寫 默認的是GET
method: 'get'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
#2.1 DELETE請求方式參數(shù)傳遞 刪除id 是 id=789
fetch('http://localhost:3000/books/789', {
method: 'delete'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
#3 POST請求傳參
fetch('http://localhost:3000/books', {
method: 'post',
# 3.1 傳遞數(shù)據(jù)
body: 'uname=lisi&pwd=123',
# 3.2 設(shè)置請求頭
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
# POST請求傳參
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: '張三',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
# PUT請求傳參 修改id 是 123 的
fetch('http://localhost:3000/books/123', {
method: 'put',
body: JSON.stringify({
uname: '張三',
pwd: '789'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
</script>

image.png
fetchAPI 中 響應(yīng)格式
- 用fetch來獲取數(shù)據(jù),如果響應(yīng)正常返回,我們首先看到的是一個response對象,其中包括返回的一堆原始字節(jié),這些字節(jié)需要在收到后,需要我們通過調(diào)用方法將其轉(zhuǎn)換為相應(yīng)格式的數(shù)據(jù),比如
JSON,BLOB或者TEXT等等
/*
Fetch響應(yīng)結(jié)果的數(shù)據(jù)格式
*/
fetch('http://localhost:3000/json').then(function(data){
// return data.json(); // 將獲取到的數(shù)據(jù)使用 json 轉(zhuǎn)換對象
return data.text(); // // 將獲取到的數(shù)據(jù) 轉(zhuǎn)換成字符串
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
axios
- 基于promise用于瀏覽器和node.js的http客戶端
- 支持瀏覽器和node.js
- 支持promise
- 能攔截請求和響應(yīng)
- 自動轉(zhuǎn)換JSON數(shù)據(jù)
- 能轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
axios基礎(chǔ)用法
axios.get('http://localhost:3000/adata').then(function(ret){
// 注意data屬性是固定的用法,用于獲取后臺的實際數(shù)據(jù)
// console.log(ret.data)
console.log(ret.data)
})
- get和 delete請求傳遞參數(shù)
- 通過傳統(tǒng)的url 以 ? 的形式傳遞參數(shù)
- restful 形式傳遞參數(shù)
- 通過params 形式傳遞參數(shù)
- post 和 put 請求傳遞參數(shù)
- 通過選項傳遞參數(shù)
- 通過 URLSearchParams 傳遞參數(shù)
# 1. 發(fā)送get 請求
axios.get('http://localhost:3000/adata').then(function(ret){
# 拿到 ret 是一個對象 所有的對象都存在 ret 的data 屬性里面
// 注意data屬性是固定的用法,用于獲取后臺的實際數(shù)據(jù)
// console.log(ret.data)
console.log(ret)
})
# 2. get 請求傳遞參數(shù)
# 2.1 通過傳統(tǒng)的url 以 ? 的形式傳遞參數(shù)
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
})
# 2.2 restful 形式傳遞參數(shù)
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
# 2.3 通過params 形式傳遞參數(shù)
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
#3 axios delete 請求傳參 傳參的形式和 get 請求一樣
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
# 4 axios 的 post 請求
# 4.1 通過選項傳遞參數(shù)
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
# 4.2 通過 URLSearchParams 傳遞參數(shù)
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
#5 axios put 請求傳參 和 post 請求一樣
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})

image.png
響應(yīng)結(jié)果
axios.get('http://localhost:3000/axios-json').then(function(ret){
console.log(ret.data.uname,ret.data.age)
})
axios 全局配置
# 配置公共的請求頭
axios.defaults.baseURL = 'https://api.example.com';
# 配置 超時時間
axios.defaults.timeout = 2500;
# 配置公共的請求頭
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
# 配置公共的 post 的 Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
- 用法
// 配置請求的基準(zhǔn)URL地址
axios.defaults.baseURL = 'http://localhost:3000/';
// 配置請求頭信息
axios.defaults.headers['mytoken'] = 'hello';
axios.get('axios-json').then(function(ret){
console.log(ret.data)
})
axios 攔截器
- 請求攔截器
- 請求攔截器的作用是在請求發(fā)送前進行一些操作
- 例如在每個請求體里加上token,統(tǒng)一做了處理如果以后要改也非常容易
- 響應(yīng)攔截器
- 響應(yīng)攔截器的作用是在接收到響應(yīng)后進行一些操作
- 例如在服務(wù)器返回登錄狀態(tài)失效,需要重新登錄的時候,跳轉(zhuǎn)到登錄頁
# 1. 請求攔截器
axios.interceptors.request.use(function(config) {
console.log(config.url)
# 1.1 任何請求都會經(jīng)過這一步 在發(fā)送請求之前做些什么
config.headers.mytoken = 'nihao';
# 1.2 這里一定要return 否則配置不成功
return config;
}, function(err){
#1.3 對請求錯誤做點什么
console.log(err)
})
#2. 響應(yīng)攔截器
axios.interceptors.response.use(function(res) {
#2.1 在接收響應(yīng)做些什么
var data = res.data;
return data;
}, function(err){
#2.2 對響應(yīng)錯誤做點什么
console.log(err)
})
async 和 await
-
async作為一個關(guān)鍵字放到函數(shù)前面
- 任何一個
async函數(shù)都會隱式返回一個promise
- 任何一個
-
await關(guān)鍵字只能在使用async定義的函數(shù)中使用- ? await后面可以直接跟一個 Promise實例對象
- ? await函數(shù)不能單獨使用
async/await 讓異步代碼看起來、表現(xiàn)起來更像同步代碼
async function queryData() {
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')
},1000);
})
return ret;
}
queryData().then(function(data){
console.log(data)
})
async/await處理多個異步任務(wù)
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData(){
var info = await axios.get('async1');
var ret = await axios.get('async2?info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})

