JS非同步程式設計之async&await
ES2017 標準中引入了 async 函式,async 函式其實是 generator 的語法糖,相較於其他非同步方法進行了用法上的改進,讓 JS 的非同步程式設計變得更加簡單和優雅。
一、async & await 用法
async function getData() { console.log(1); const response = await fetch("https://api.apiopen.top/getJoke?page=1&count=2&type=video", { mode: 'cors', headers: { 'Content-Type': 'application/json' } }); console.log(2); return response.json(); } getData() .then(res => { console.log(res); console.log(3); }) console.log(4);// 1 42 3 複製程式碼
async 函式總是會返回 Promise 物件,Promise.then() 回撥方法的引數是 async 函式 return 的值。
async 函式在執行時會在 await 關鍵字語句掛起暫停執行,等待 await 右邊的非同步方法完成後再以 Promise.then() 的形式執行內部下面的語句,雖然會阻塞 await下面的程式碼執行,但是並不會阻塞外部主執行緒方法的執行。
二、錯誤捕捉
async function getData() { // throw new Error("報錯啦") try { throw new Error("報錯啦") console.log(123456) return response; } catch (error) { console.log(error); } } getData() .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }) 複製程式碼
如果 async 函式中有 try catch,那麼 async 函式將直接捕捉並處理到內部的錯誤, 不會繼續執行後面的程式碼。而如果 async 函式中沒有 try catch,那麼錯誤會導致返回的 Promise 直接轉移到 rejected 狀態,進而在返回的 Promise.catch() 方法中捕捉到。
三、async & await 應用
我們再一次封裝 ajax 方法~
const Ajax = ({ method = 'get', url = '/', data, async = true }) => { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest() xhr.onreadystatechange = () => { if (xhr.readyState === 4 && xhr.status === 200) { let res = JSON.parse(xhr.responseText) resolve(res) } } xhr.open(method, url, async) if (method === 'get') { xhr.send(); } if (method === 'post') { let type = typeof data let header if (type === 'string') { header = 'application/x-www-form-urlencoded' } else { header = 'application/json' data = JSON.stringify(data) } xhr.setRequestHeader('Content-type', header) xhr.send(data); } }) } Ajax.get = (url) => { return Ajax({url}) } async function getData() { try { let data = await Ajax.get('https://api.apiopen.top/getJoke?page=1&count=2&type=video') return data; } catch (error) { console.log(error); } } getData() .then(res => { console.log(res); }) 複製程式碼
總結
async&await 是結合 Promise 鏈式呼叫和 Generator 暫停執行的特點,且封裝了 Generator 自執行函式,讓程式碼看起來更像是同步執行,是未來非同步程式設計的發展方向。