# 章節導航
[TOC]
## 介紹
當有很多事情發生時,異步代碼很難理解。`async`并且`await`是兩個關鍵字,可以幫助使異步讀取更像同步代碼。這可以幫助代碼看起來更干凈,同時保持異步代碼的好處。
例如,下面的兩個代碼塊完全相同,它們都從服務器獲取信息,處理它并返回一個promise。
```
function getPersonsInfo(name){
return server.getPeople()
.then((people)=>{
return people.find(person =>{return person.name === name});
})
}
```
```
async function getPersonsInfo(name){
const people = await server.getPeople();
const person = people.find(person =>{
return person.name ===name
});
}
```
## 學習成果
1. How do you declare an`async`function?
2. What does the`async`keyword do?
3. What does the`await`keyword do?
4. What is returned from an`async`function?
5. What happens when an error is thrown inside an`async`function?
6. How can you handle errors inside an`async`function?
## async關鍵字
該`async`關鍵字是什么讓JavaScript引擎知道你是聲明一個異步函數,這是需要使用`await`任何函數內。當聲明一個函數時`async`,它會自動返回一個promise,在`async`函數中返回與解析一個promise相同,同樣拋出一個錯誤將拒絕這個promise。
要理解的重要一點時async函數只是語法promises
該async關鍵字也可以與任何一個功能可以創建使用方式,不同的說:它是有效的使用async功能,隨時隨地可以使用正常的功能。下面您將看到一些可能不直觀的示例,如果你不理解可以完成作業后再回頭看
```
const yourAsyncFunction = async() => {
return result;
//do something asynchronously and return a promise
}
```
```
anArray.forEach(async(item) =>{
// dom something asynchronously for each item in 'anArray'
//one could also use .map here to return an array of promises to use with 'Promise.all()'
})
```
```
server.getPeople().then(async(people)=>{
people.forEach((person)=>{
//do something asynchronously for each person
});
})
```
### [await關鍵字]
`await`非常簡單:它告訴javascript在繼續執行函數之前等待異步操作完成。它就像一個'暫停直到'關鍵字。該`await`關鍵字用于從通常使用的函數中獲取值`.then()`。您不必`.then()`在異步函數之后調用,只需使用變量為結果賦值`await`,然后就可以像在同步代碼中一樣使用代碼中的結果。
### [錯誤處理]
處理`async`函數中的錯誤非常容易。Promises有`.catch()`處理被拒絕的promises的方法,并且由于異步函數只返回一個promise,你可以簡單地調用該函數,并`.catch()`在最后添加一個方法。
~~~javascript
asyncFunctionCall().catch((err) => {console.error(err)});
~~~
但還有另一種方式:強大的`try/catch`阻擋!如果要直接在`async`函數內部處理錯誤,可以`try/catch`像在同步代碼中一樣使用。
但還有另一種方式:強大的`try/catch`阻擋!如果要直接在`async`函數內部處理錯誤,可以`try/catch`像在同步代碼中一樣使用。
~~~javascript
async function getPersonsInfo(name) {
try {
const people = await server.getPeople();
const person = people.find(person => { return person.name === name });
return person;
} catch (error) {
// Handle the error any way you'd like
}
}
~~~
這樣做看起來很麻煩,但這是一種非常簡單的方法來處理錯誤,而不會`.catch()`在函數調用后附加。您如何處理錯誤取決于您,您使用的方法應該由您的代碼編寫方式決定。您將了解隨著時間的推移需要做些什么。作業還將幫助您了解如何處理錯誤
## 實踐
還記得Giphy API實踐項目嗎?(如果沒有,您應該返回并完成API課程)。我們將基于promise的代碼轉換為`async/await`兼容代碼。以下是我們開始使用的代碼的復習:
```
<script>
const img = document.querySelector('img');
fetch('https://api.giphy.com/v1/gifs/translate?api_key=bb2006d9d3454578be1a99cfad65913d&s=cat', {mode: 'cors'})
.then(function(response) {
return response.json()
})
.then(function(response) {
img.serc = response.data.images.original.url
})
</script>
```
由于`await`不適用于全局范圍,我們必須創建一個`async`包含我們對Giphy的API調用的函數。
~~~javascript
<script>
const img = document.querySelector('img')
async function getCats() {
fetch('https://api.giphy.com/v1/gifs/translate?api_key=111111&s=cats', {mode: 'cors'})
.then(function(response) {
return response.json()
})
.then(function(response) {
img.src = response.data.images.original.url;
})
}
</script>
~~~
既然我們有一個異步的函數,那么我們就可以開始使用promises進行重構`await`
~~~javascript
<script>
const img = document.querySelector('img')
async function getCats() {
const response = await fetch('https://api.giphy.com/v1/gifs/translate?api_key=111111&s=cats', {mode: 'cors'});
response.json()
.then(function(response) {
img.src = response.data.images.original.url;
});
}
</script>
~~~
由于`response`仍然是我們`.then()`在開始時傳遞給塊的同一個對象,我們仍然需要使用該`.json()`方法,而該方法又返回一個promise。因為`.json()`返回一個promise,我們可以`await`用來將響應分配給一個變量。
~~~javascript
<script>
const img = document.querySelector('img')
async function getCats() {
const response = await fetch('https://api.giphy.com/v1/gifs/translate?api_key=111111&s=cats', {mode: 'cors'});
const catData = await response.json();
img.src = catData.data.images.original.url;
}
</script>
~~~
要使用此功能,我們只需要`getCats()`在代碼中調用它。
~~~javascript
<script>
const img = document.querySelector('img')
async function getCats() {
const response = await fetch('https://api.giphy.com/v1/gifs/translate?api_key=111111&s=cats', {mode: 'cors'});
const catData = await response.json();
img.src = catData.data.images.original.url;
}
getCats();
</script>
~~~
此代碼的行為與上一課中的代碼完全相同,重構后看起來有點不同。`async/await`在清理異步的JavaScript代碼時,它們是非常有用的工具。重要的的英文要記住`async/await`只是以不同方式寫的承諾。做下面的任務,深入了解`async/await`。
- 前言
- 你真的懂This嗎?
- 對象和對象構造函數
- 工廠功能和模塊模式
- API的使用
- async and await
- 關于async的很棒的一篇文章
- 掘金:關于forEach,map,fiter循環操作
- Node.js 實例與基礎
- 原創: Express 學習使用筆記
- 零碎知識點方法
- 關于滾動吸頂的方法
- Vue學習筆記
- Vue向導
- vuex是啥?
- vue代碼風格指南
- 關于vue的初體驗
- 超詳細解毒Vue
- Vue實例
- 模版語言
- 組件基礎
- 條件渲染、列表渲染、Class與style綁定
- Todolist的制作超詳細
- vue-router
- Vue基礎2.0x 筆記
- 搭建vuepress
- JavaScript之ES6
- 箭頭函數
- 這就是This