## async-await 與其他方式對比
async / await 是 ES2017中引入的,為了使異步操作得更加方便,本質上 async 函數是 Generator 函數的語法糖。
async 函數書寫的方式跟我們普通的函數書寫方式一樣,只不過是前面多了一個 async 關鍵字,并且函數返回的是一個 Promise 對象,所接收的值就是函數 return 的值。
在 async 函數內部可以使用 await 命令,表示等待一個異步函數的返回。await 后面跟著的是一個 Promise 對象,如果不是的話,系統會調用 Promise.resolve() 方法,將其轉為一個 resolve 的 Promise 的對象。
假設有那么一個異步函數 :
```
function p (num) {
if (num >= 0) {
return Promise.resolve(num)
} else {
return Promise.reject(new Error('參數不能小于 0'))
}
}
```
### 普通的 Promise 調用方式 :
```
console.log('-1-')
p(1).then(data => {
console.log(data)
retrun p(2)
}).then(data => {
console.log(data)
})
console.log('-2-')
```
輸出
```
-1-
-2-
1
2
```
### 使用 Generator 調用方式
```
function *gen() {
yield p(1)
yield p(2)
}
let g = gen()
console.log('-1-')
g.next().value.then(data => {
console.log(data)
return g.next().value
}).then(data => {
console.log(data)
return g.next().value
}).then(console.log)
console.log('-2-')
```
輸出
```
-1-
-2-
1
2
undefined
```
### 使用 async-await 方式 :
```
async function ps() {
let a = await p(1)
console.log(a)
let b = await p(2)
console.log(b)
return [a, b]
}
console.log('-1-')
ps().then(res => {
console.log(res)
})
console.log('-2-')
```
輸出
```
-1-
-2-
1
2
[1, 2]
```