1.定義
調用MDN中的說法:定義一個返回 AsyncFunction 對象的異步函數。異步函數是指通過事件循環異步執行的函數,它會通過一個隱式的 Promise 返回其結果。
並且在使用async函數的過程中,會更像同步函數的用法,更易於理解
2.用法
1.函數中用async
在函數前面進行標註,表明是異步函數。
2.在異步執行語句前添加await
關鍵字,該指令會暫停異步函數的執行,並等待Promise執行,通常這種語句是會返回一個Promise
。
3.異步執行語句返回的值時是指promise
對象中的執行resolve
函數的參數值;我的個人理解,不知道網上爲啥說的這麼複雜。
4.async
函數最終返回的也是一個promise
對象,所以可以在它後面使用then
函數。
async function Async1() {
return "hi";
}
async function Async2() {
return Promise.resolve('hello')
}
注意
await 關鍵字只在異步函數內有效。如果你在異步函數外使用它,會拋出語法錯誤。
附上vue使用async函數簡單解決axios請求
export default {
name: 'Historys',
data() {
return {
totalData: 0,
tableData: []
}
},
created () {
this.getHistoryData()
},
methods: {
handleClick (tab) {
let data = {
status: tab.name,
name: this.formInline.user,
cid: this.formInline.identity,
start_time: this.formInline.dateTime ? this.formInline.dateTime[0] : '',
end_time: this.formInline.dateTime ? this.formInline.dateTime[1] : ''
}
this.getHistoryData()
},
// 統一處理axios請求
async getHistoryData (data) {
try {
let res = await axios.get('/api/survey/list/', {
params: data
})
this.tableData = res.data.result
this.totalData = res.data.count
} catch (err) {
console.log(err)
alert('請求出錯!')
}
}
}
}