要了解 JavaScript Async Await 之前, 你需要先認識 Promise !
還不知道 Promise 的點這裡看文章! 關於 JavaScript Promises
Async Await 是甚麼?
字面上解釋:
Async : 非同步
Await : 等待
簡單來說 Async Await 的功用就是: 讓promise在執行時,執行完一個再跑下一個。
在 Promise 介紹文章中,有介紹到 Promise Chain ,我們運用 Promise Chain 確保第一個執行完後,透過return帶入到下一個then中。但是這樣的寫法,有點繁瑣複雜,因此在 ES7 有了 Async Await 的出現。
Async Await 就是 Promise 的糖果衣,讓Promise看起來更簡單。
Async Await 運用
情境:
function makeRequest(location){
return new Promise((resolve,reject)=>{
console.log(`making request to ${location}`)
if(location === 'Google'){
resolve('Google says Hi')
}else{
reject('We can only talk to Google')
}
})
};
function processRequest(response){
return new Promise((resolve,reject) => {
console.log('Processing response')
resolve(`Extra Information + ${response}`)
})
}
使用 Promise Chain :
makeRequest('Google').then(response => { // making request to Google
console.log('Resonse Received') // Resonse Received
return processRequest(response)
}).then(processResponse => { // Processing response
console.log(processResponse) // Extra Information + Google says Hi
}).catch(err => {
console.log(err)
})
使用 Async Await :
使用的注意事項:
- Awating code must be inside a function.
- This function must let JavaScript know it's dealing with Awating code, as a result, at the begining of that function needs to add the word -'async'.
- How to handle with error: use try and catch
async function doWork(){
const response = await makeRequest('Google'); // await 就是表示 需要等到這個完成才能繼續執行。
const processResponse = await processRequest(response);
console.log(processResponse)
}
doWork();
How to handle with error
將任何有可能出錯的,放入try{}中
async function doWork(){
try{
const response = await makeRequest('Google'); // await 就是表示 需要等到這個完成才能繼續執行。
const processResponse = await processRequest(response);
console.log(processResponse)
}
catch(err){
console.log(err)
}
}
doWork();
CodePen - JavaScript Async Await