# Async/await 和 Promises 區別
1. Async/await 是建立在 Promises上的,不能被使用在普通回調以及節點回調
2. Async/await 和 Promises 很像,不阻塞
3. Async/await 代碼看起來像同步代碼。
## 語法
假設函數`getJSON`返回值是 Promise,并且 Promise resolves 有一些JSON 對象。我們只想調用它并且記錄該`JSON`并且返回完成。
**使用Promise**
~~~
const makeRequest = () =>
getJSON()
.then(data => {
console.log(data)
return "done"
})
makeRequest()
~~~
**使用Async**
~~~
const makeRequest = async() => {
console.log(await getJSON)
return "done"
}
makeRequest()
~~~
### 區別
1. 在函數前有一個關鍵字`async`,`await`關鍵字只能在使用`async`定義的函數中使用。任何一個`async`函數都會隱式返回一個`promise`,并且promise resolve 的值就是 return 返回的值 (例子中是”done”)
2. 不能在函數開頭使用`await`
### 有哪些好處
1. 簡潔的代碼
使用async函數可以讓代碼簡潔很多,不需要像Promise一樣需要些then
1. 錯誤處理
Promise 中不能自定義使用 try/catch 進行錯誤捕獲,但是在 Async/await 中可以像處理同步代碼處理錯誤
~~~
const makeRequest = () => {
try {
getJSON()
.then(result => {
// this parse may fail
const data = JSON.parse(result)
console.log(data)
})
// uncomment this block to handle asynchronous errors
// .catch((err) => {
// console.log(err)
// })
} catch (err) {
console.log(err)
}
}
~~~
Async/await
~~~
const makeRequest = async () => {
try {
// this parse may fail
const data = JSON.parse(await getJSON())
console.log(data)
} catch (err) {
console.log(err)
}
}
~~~
1. 條件語句
條件語句也和錯誤捕獲是一樣的,在 Async 中也可以像平時一般使用條件語句
Promise
~~~
const makeRequest = () => {
return getJSON()
.then(data => {
if (data.needsAnotherRequest) {
return makeAnotherRequest(data)
.then(moreData => {
console.log(moreData)
return moreData
})
} else {
console.log(data)
return data
}
})
}
~~~
Async
~~~
const makeRequest = async () => {
const data = await getJSON()
if (data.needsAnotherRequest) {
const moreData = await makeAnotherRequest(data);
console.log(moreData)
return moreData
} else {
console.log(data)
return data
}
}
~~~
1. 中間值
在一些場景中,也許需要 `promise1` 去觸發 `promise2` 再去觸發 `promise3`,這個時候代碼應該是這樣的
~~~
const makeRequest = () => {
return promise1()
.then(value1 => {
// do something
return promise2(value1)
.then(value2 => {
// do something
return promise3(value1, value2)
})
})
}
~~~
如過 `promise3` 不需要 `value1`,嵌套將會變得簡單。如果你有強迫癥,則將值1&2使用 `promise.all()` 分裝起來。
~~~
const makeRequest = () => {
return promise1()
.then(value1 => {
// do something
return Promise.all([value1, promise2(value1)])
})
.then(([value1, value2]) => {
// do something
return promise3(value1, value2)
})
}
~~~
但是使用 `Async` 就會變得很簡單
~~~
const makeRequest = async () => {
const value1 = await promise1()
const value2 = await promise2(value1)
return promise3(value1, value2)
}
~~~
1. 錯誤棧
如過 Promise 連續調用,對于錯誤的處理是很麻煩的。你無法知道錯誤出在哪里。
~~~
const makeRequest = () => {
return callAPromise()
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => {
throw new Error("oops");
})
}
makeRequest()
.catch(err => {
console.log(err);
// output
// Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
})
~~~
但是對于 Async 就不一樣了
~~~
const makeRequest = async () => {
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
throw new Error("oops");
}
makeRequest()
.catch(err => {
console.log(err);
// output
// Error: oops at makeRequest (index.js:7:9)
})
~~~
- 內容介紹
- EcmaScript基礎
- 快速入門
- 常量與變量
- 字符串
- 函數的基本概念
- 條件判斷
- 數組
- 循環
- while循環
- for循環
- 函數基礎
- 對象
- 對象的方法
- 函數
- 變量作用域
- 箭頭函數
- 閉包
- 高階函數
- map/reduce
- filter
- sort
- Promise
- 基本對象
- Arguments 對象
- 剩余參數
- Map和Set
- Json基礎
- RegExp
- Date
- async
- callback
- promise基礎
- promise-api
- promise鏈
- async-await
- 項目實踐
- 標簽系統
- 遠程API請求
- 面向對象編程
- 創建對象
- 原型繼承
- 項目實踐
- Classes
- 構造函數
- extends
- static
- 項目實踐
- 模塊
- import
- export
- 項目實踐
- 第三方擴展庫
- immutable
- Vue快速入門
- 理解MVVM
- Vue中的MVVM模型
- Webpack+Vue快速入門
- 模板語法
- 計算屬性和偵聽器
- Class 與 Style 綁定
- 條件渲染
- 列表渲染
- 事件處理
- 表單輸入綁定
- 組件基礎
- 組件注冊
- Prop
- 自定義事件
- 插槽
- 混入
- 過濾器
- 項目實踐
- 標簽編輯
- iView
- iView快速入門
- 課程講座
- 環境配置
- 第3周 Javascript快速入門