用 async/await 來處理異步
昨天看了一篇vue的教程,作者用async/ await來發(fā)送異步請求,從服務(wù)端獲取數(shù)據(jù),代碼很簡潔,同時async/await 已經(jīng)被標(biāo)準(zhǔn)化,是時候?qū)W習(xí)一下了。
先說一下async的用法,它作為一個關(guān)鍵字放到函數(shù)前面,用于表示函數(shù)是一個異步函數(shù),因為async就是異步的意思, 異步函數(shù)也就意味著該函數(shù)的執(zhí)行不會阻塞后面代碼的執(zhí)行。 寫一個async 函數(shù)
<pre style="margin: 0px; padding: 0px;">async function timeout() {
return 'hello world';
}</pre>
語法很簡單,就是在函數(shù)前面加上async 關(guān)鍵字,來表示它是異步的,那怎么調(diào)用呢?async 函數(shù)也是函數(shù),平時我們怎么使用函數(shù)就怎么使用它,直接加括號調(diào)用就可以了,為了表示它沒有阻塞它后面代碼的執(zhí)行,我們在async 函數(shù)調(diào)用之后加一句console.log;
<pre style="margin: 0px; padding: 0px;">async function timeout() {
return 'hello world'
}
timeout();
console.log('雖然在后面,但是我先執(zhí)行');</pre>
打開瀏覽器控制臺,我們看到了

async 函數(shù) timeout 調(diào)用了,但是沒有任何輸出,它不是應(yīng)該返回 'hello world', 先不要著急, 看一看timeout()執(zhí)行返回了什么? 把上面的 timeout() 語句改為console.log(timeout())
<pre style="margin: 0px; padding: 0px;">async function timeout() {
return 'hello world'
}
console.log(timeout());
console.log('雖然在后面,但是我先執(zhí)行');</pre>
繼續(xù)看控制臺

原來async 函數(shù)返回的是一個promise 對象,如果要獲取到promise 返回值,我們應(yīng)該用then 方法, 繼續(xù)修改代碼

<pre style="margin: 0px; padding: 0px;">async function timeout() {
return 'hello world'
}
timeout().then(result => {
console.log(result);
})
console.log('雖然在后面,但是我先執(zhí)行');</pre>

看控制臺

我們獲取到了"hello world', 同時timeout 的執(zhí)行也沒有阻塞后面代碼的執(zhí)行,和 我們剛才說的一致。
這時,你可能注意到控制臺中的Promise 有一個resolved,這是async 函數(shù)內(nèi)部的實現(xiàn)原理。如果async 函數(shù)中有返回一個值 ,當(dāng)調(diào)用該函數(shù)時,內(nèi)部會調(diào)用Promise.solve() 方法把它轉(zhuǎn)化成一個promise 對象作為返回,但如果timeout 函數(shù)內(nèi)部拋出錯誤呢? 那么就會調(diào)用Promise.reject() 返回一個promise 對象, 這時修改一下timeout 函數(shù)

<pre style="margin: 0px; padding: 0px;">async function timeout(flag) {
if (flag) {
return 'hello world'
} else {
throw 'my god, failure'
}
}
console.log(timeout(true)) // 調(diào)用Promise.resolve() 返回promise 對象。
console.log(timeout(false)); // 調(diào)用Promise.reject() 返回promise 對象。</pre>

控制臺如下:

如果函數(shù)內(nèi)部拋出錯誤, promise 對象有一個catch 方法進(jìn)行捕獲。
<pre style="margin: 0px; padding: 0px;">timeout(false).catch(err => {
console.log(err)
})</pre>
async 關(guān)鍵字差不多了,我們再來考慮await 關(guān)鍵字,await是等待的意思,那么它等待什么呢,它后面跟著什么呢?其實它后面可以放任何表達(dá)式,不過我們更多的是放一個返回promise 對象的表達(dá)式。注意await 關(guān)鍵字只能放到async 函數(shù)里面
現(xiàn)在寫一個函數(shù),讓它返回promise 對象,該函數(shù)的作用是2s 之后讓數(shù)值乘以2

<pre style="margin: 0px; padding: 0px;">// 2s 之后返回雙倍的值
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
} )
}</pre>

現(xiàn)在再寫一個async 函數(shù),從而可以使用await 關(guān)鍵字, await 后面放置的就是返回promise對象的一個表達(dá)式,所以它后面可以寫上 doubleAfter2seconds 函數(shù)的調(diào)用
<pre style="margin: 0px; padding: 0px;">async function testResult() {
let result = await doubleAfter2seconds(30);
console.log(result);
}</pre>
現(xiàn)在調(diào)用testResult 函數(shù)
<pre style="margin: 0px; padding: 0px;">testResult();</pre>
打開控制臺,2s 之后,輸出了60.
現(xiàn)在我們看看代碼的執(zhí)行過程,調(diào)用testResult 函數(shù),它里面遇到了await, await 表示等一下,代碼就暫停到這里,不再向下執(zhí)行了,它等什么呢?等后面的promise對象執(zhí)行完畢,然后拿到promise resolve 的值并進(jìn)行返回,返回值拿到之后,它繼續(xù)向下執(zhí)行。具體到 我們的代碼, 遇到await 之后,代碼就暫停執(zhí)行了, 等待doubleAfter2seconds(30) 執(zhí)行完畢,doubleAfter2seconds(30) 返回的promise 開始執(zhí)行,2秒 之后,promise resolve 了, 并返回了值為60, 這時await 才拿到返回值60, 然后賦值給result, 暫停結(jié)束,代碼才開始繼續(xù)執(zhí)行,執(zhí)行 console.log語句。
就這一個函數(shù),我們可能看不出async/await 的作用,如果我們要計算3個數(shù)的值,然后把得到的值進(jìn)行輸出呢?

<pre style="margin: 0px; padding: 0px;">async function testResult() {
let first = await doubleAfter2seconds(30);
let second = await doubleAfter2seconds(50);
let third = await doubleAfter2seconds(30);
console.log(first + second + third);
}</pre>

6秒后,控制臺輸出220, 我們可以看到,寫異步代碼就像寫同步代碼一樣了,再也沒有回調(diào)地域了。
再寫一個真實的例子,我原來做過一個小功能,話費(fèi)充值,當(dāng)用戶輸入電話號碼后,先查找這個電話號碼所在的省和市,然后再根據(jù)省和市,找到可能充值的面值,進(jìn)行展示。
為了模擬一下后端接口,我們新建一個node 項目。 新建一個文件夾 async, 然后npm init -y 新建package.json文件,npm install express --save 安裝后端依賴,再新建server.js 文件作為服務(wù)端代碼, public文件夾作為靜態(tài)文件的放置位置, 在public 文件夾里面放index.html 文件, 整個目錄如下

server.js 文件如下,建立最簡單的web 服務(wù)器

<pre style="margin: 0px; padding: 0px;">const express = require('express');
const app = express();// express.static 提供靜態(tài)文件,就是html, css, js 文件
app.use(express.static('public'));
app.listen(3000, () => {
console.log('server start');
})</pre>

再寫index.html 文件,我在這里用了vue構(gòu)建頁面,用axios 發(fā)送ajax請求, 為了簡單,用cdn 引入它們。 html部分很簡單,一個輸入框,讓用戶輸入手機(jī)號,一個充值金額的展示區(qū)域, js部分,按照vue 的要求搭建了模版

<pre style="margin: 0px; padding: 0px;"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Async/await</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<!-- 輸入框區(qū)域 -->
<div style="height:50px">
<input type="text" placeholder="請輸入電話號碼" v-model="phoneNum">
<button @click="getFaceResult">確定</button>
</div>
<!-- 充值面值 顯示區(qū)域 -->
<div>
充值面值:
<span v-for="item in faceList" :key='item'>
{{item}}
</span>
</div>
</div>
<!-- js 代碼區(qū)域 -->
<script>
new Vue({
el: '#app',
data: {
phoneNum: '12345',
faceList: ["20元", "30元", "50元"]
},
methods: {
getFaceResult() {
}
}
})
</script>
</body>
</html></pre>

為了得到用戶輸入的手機(jī)號,給input 輸入框添加v-model指令,綁定phoneNum變量。展示區(qū)域則是 綁定到faceList 數(shù)組,v-for 指令進(jìn)行展示, 這時命令行nodemon server 啟動服務(wù)器,如果你沒有安裝nodemon, 可以npm install -g nodemon 安裝它。啟動成功后,在瀏覽器中輸入 http://localhost:3000, 可以看到頁面如下, 展示正確

現(xiàn)在我們來動態(tài)獲取充值面值。當(dāng)點(diǎn)擊確定按鈕時, 我們首先要根據(jù)手機(jī)號得到省和市,所以寫一個方法來發(fā)送請求獲取省和市,方法命名為getLocation, 接受一個參數(shù)phoneNum , 后臺接口名為phoneLocation,當(dāng)獲取到城市位置以后,我們再發(fā)送請求獲取充值面值,所以還要再寫一個方法getFaceList, 它接受兩個參數(shù), province 和city, 后臺接口為faceList,在methods 下面添加這兩個方法getLocation, getFaceList

<pre style="margin: 0px; padding: 0px;"> methods: {
//獲取到城市信息
getLocation(phoneNum) {
return axios.post('phoneLocation', {
phoneNum
})
},
// 獲取面值
getFaceList(province, city) {
return axios.post('/faceList', {
province,
city
})
},
// 點(diǎn)擊確定按鈕時,獲取面值列表
getFaceResult () {
}
}</pre>

現(xiàn)在再把兩個后臺接口寫好,為了演示,寫的非常簡單,沒有進(jìn)行任何的驗證,只是返回前端所需要的數(shù)據(jù)。Express 寫這種簡單的接口還是非常方便的,在app.use 和app.listen 之間添加如下代碼

<pre style="margin: 0px; padding: 0px;">// 電話號碼返回省和市,為了模擬延遲,使用了setTimeout
app.post('/phoneLocation', (req, res) => {
setTimeout(() => {
res.json({
success: true,
obj: {
province: '廣東',
city: '深圳'
}
})
}, 1000);
})
// 返回面值列表
app.post('/faceList', (req, res) => {
setTimeout(() => {
res.json(
{
success: true,
obj:['20元', '30元', '50元']
}
)
}, 1000);
})</pre>

最后是前端頁面中的click 事件的getFaceResult, 由于axios 返回的是promise 對象,我們使用then 的鏈?zhǔn)綄懛?,先調(diào)用getLocation方法,在其then方法中獲取省和市,然后再在里面調(diào)用getFaceList,再在getFaceList 的then方法獲取面值列表,

<pre style="margin: 0px; padding: 0px;"> // 點(diǎn)擊確定按鈕時,獲取面值列表
getFaceResult () {
this.getLocation(this.phoneNum)
.then(res => {
if (res.status === 200 && res.data.success) {
let province = res.data.obj.province;
let city = res.data.obj.city;
this.getFaceList(province, city)
.then(res => {
if(res.status === 200 && res.data.success) {
this.faceList = res.data.obj
}
})
}
})
.catch(err => {
console.log(err)
})
}</pre>

現(xiàn)在點(diǎn)擊確定按鈕,可以看到頁面中輸出了 從后臺返回的面值列表。這時你看到了then 的鏈?zhǔn)綄懛?,有一點(diǎn)回調(diào)地域的感覺?,F(xiàn)在我們在有async/ await 來改造一下。
首先把 getFaceResult 轉(zhuǎn)化成一個async 函數(shù),就是在其前面加async, 因為它的調(diào)用方法和普通函數(shù)的調(diào)用方法是一致,所以沒有什么問題。然后就把 getLocation 和
getFaceList 放到await 后面,等待執(zhí)行, getFaceResult 函數(shù)修改如下

<pre style="margin: 0px; padding: 0px;"> // 點(diǎn)擊確定按鈕時,獲取面值列表
async getFaceResult () {
let location = await this.getLocation(this.phoneNum);
if (location.data.success) {
let province = location.data.obj.province;
let city = location.data.obj.city;
let result = await this.getFaceList(province, city);
if (result.data.success) {
this.faceList = result.data.obj;
}
}
}</pre>

現(xiàn)在代碼的書寫方式,就像寫同步代碼一樣,沒有回調(diào)的感覺,非常舒服。
現(xiàn)在就還差一點(diǎn)需要說明,那就是怎么處理異常,如果請求發(fā)生異常,怎么處理? 它用的是try/catch 來捕獲異常,把a(bǔ)wait 放到 try 中進(jìn)行執(zhí)行,如有異常,就使用catch 進(jìn)行處理。

<pre style="margin: 0px; padding: 0px;"> async getFaceResult () {
try {
let location = await this.getLocation(this.phoneNum);
if (location.data.success) {
let province = location.data.obj.province;
let city = location.data.obj.city;
let result = await this.getFaceList(province, city);
if (result.data.success) {
this.faceList = result.data.obj;
}
}
} catch(err) {
console.log(err);
}
}</pre>

現(xiàn)在把服務(wù)器停掉,可以看到控制臺中輸出net Erorr,整個程序正常運(yùn)行。