這篇文章詳細(xì)講解了JavaScript中的異步函數(shù)。 JavaScript中的異步代碼在很短的時(shí)間內(nèi)從回調(diào)發(fā)展為Promise渠鸽,再到ES2017的異步函數(shù)柴罐,現(xiàn)在我們可以像編寫(xiě)同步代碼那樣編寫(xiě)基于 Promise 的代碼革屠,而且還不會(huì)阻塞主線程。
為什么需要async/await似芝?
當(dāng)promise在ES2015中引入時(shí)党瓮,目的是解決異步代碼的問(wèn)題,但是promise不是最終的解決方案寞奸。
雖然Promise解決了著名的回調(diào)地獄,但是它自己引入了語(yǔ)法復(fù)雜性隐岛。
所以ES2017增加了異步函數(shù)聚凹,提高了代碼可讀性齐帚,對(duì)不太熟悉 Promise 的人而言,幫助就更大了对妄。
async/await使代碼看起來(lái)像是同步的饥伊,但它在后臺(tái)是異步和非阻塞的。
工作原理
異步函數(shù)返回一個(gè)promise愉豺,如下例所示:
const doSomethingAsync = () => {
return new Promise((resolve) => {
setTimeout(() => resolve('I did something'), 3000)
})
}
調(diào)用一個(gè)異步函數(shù)時(shí)茫因,您先要設(shè)置一個(gè)await,當(dāng)您 await 某個(gè) Promise 時(shí)驰贷,函數(shù)暫停執(zhí)行括袒,直至該 Promise 產(chǎn)生結(jié)果稿茉,并且暫停并不會(huì)阻塞主線程芥炭。 如果 Promise 執(zhí)行园蝠,則會(huì)返回值痢士。 如果 Promise 拒絕,則會(huì)拋出拒絕的值陪汽。因?yàn)楫惒胶瘮?shù)去掉了所有回調(diào)褥蚯。提高了代碼的可讀性,這是一個(gè)例子:
const doSomething = async () => {
console.log(await doSomethingAsync())
}
一個(gè)簡(jiǎn)單的例子
這是異步函數(shù)async / await的簡(jiǎn)單示例:
const doSomethingAsync = () => {
return new Promise((resolve) => {
setTimeout(() => resolve('I did something'), 3000)
})
}
const doSomething = async () => {
console.log(await doSomethingAsync())
}
console.log('Before')
doSomething()
console.log('After')
上面代碼執(zhí)行結(jié)果如下:
Before
After
//after 3s
I did something
Promise詳解
將async關(guān)鍵字添加到任何函數(shù)意味著該函數(shù)將返回一個(gè)promise。即使它沒(méi)有聲明歧强,它也會(huì)在內(nèi)部使它返回一個(gè)promise。
這就是此代碼有效的原因:
const aFunction = async () => {
return 'test'
}
// This will alert 'test'
aFunction().then(alert)
它和以下一樣:
const aFunction = async () => {
return Promise.resolve('test')
}
// This will alert 'test'
aFunction().then(alert)
代碼更易讀
正如上面示例所見(jiàn)肤京,與回調(diào)和promise代碼相比茅特,異步函數(shù)代碼看起來(lái)非常簡(jiǎn)單白修。
我們下面用更復(fù)雜一點(diǎn)的代碼來(lái)演示。
例如肯骇,以下是使用promises獲取JSON資源并解析它的方法:
const getFirstUserData = () => {
// get users list
return fetch('/users.json')
// parse JSON
.then(response => response.json())
// pick first user
.then(users => users[0])
// get user data
.then(user => fetch(`/users/${user.name}`))
// parse JSON
.then(userResponse => response.json())
}
getFirstUserData()
以下是使用await / async提供的相同功能:
const getFirstUserData = async () => {
// get users list
const response = await fetch('/users.json')
// parse JSON
const users = await response.json()
// pick first user
const user = users[0]
// get user data
const userResponse = await fetch(`/users/${user.name}`)
// parse JSON
const userData = await user.json()
return userData
}
getFirstUserData()
鏈接多個(gè)異步函數(shù)
異步函數(shù)可以非常容易地鏈接笛丙,并且語(yǔ)法比簡(jiǎn)單的promise更具可讀性:
const promiseToDoSomething = () => {
return new Promise(resolve => {
setTimeout(() => resolve('I did something'), 10000)
})
}
const watchOverSomeoneDoingSomething = async () => {
const something = await promiseToDoSomething()
return something + ' and I watched'
}
const watchOverSomeoneWatchingSomeoneDoingSomething = async () => {
const something = await watchOverSomeoneDoingSomething()
return something + ' and I watched as well'
}
watchOverSomeoneWatchingSomeoneDoingSomething().then((res) => {
console.log(res)
})
將打优哐臁:
I did something and I watched and I watched as well
調(diào)試更簡(jiǎn)單
調(diào)試promise很難拆融,因?yàn)檎{(diào)試器不會(huì)調(diào)試異步代碼啊终。
Async / await使得這非常簡(jiǎn)單傲须,因?yàn)榫拖裾{(diào)試同步代碼一樣趟脂。