ES2017 標準中引入了 async 函數,async 函數實際上是 generator 的語法糖,相較於其餘異步方法進行了用法上的改進,讓 JS 的異步編程變得更加簡單和優雅。javascript
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 4 2 3
複製代碼
async 函數老是會返回 Promise 對象,Promise.then() 回調方法的參數是 async 函數 return 的值。java
async 函數在執行時會在 await 關鍵字語句掛起暫停執行,等待 await 右邊的異步方法完成後再以 Promise.then() 的形式執行內部下面的語句,雖然會阻塞 await 下面的代碼執行,可是並不會阻塞外部主線程方法的執行。ajax
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() 方法中捕捉到。編程
咱們再一次封裝 ajax 方法~json
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 自執行函數,讓代碼看起來更像是同步執行,是將來異步編程的發展方向。api