async & await & promise
async & await & promise
ES7
const f = async () => {
return 1;
};
f().then(value => console.log(value));
// 1
// Promise {<resolved>: undefined}
f();
// Promise {<resolved>: 1}
chrome://extensions/
async getNews() {
try {
const response = await fetch(`https://raw.githubusercontent.com/darkreader/darkreader.org/master/src/blog/posts.json?nocache=${Date.now()}`, { cache: 'no-cache' });
const $news = await response.json();
return new Promise((resolve, reject) => {
chrome.storage.sync.get({ readNews: [] }, ({ readNews }) => {
const news = $news.map(({ id, date, headline }) => {
const url = getBlogPostURL(id);
const read = this.isRead(id, readNews);
return { id, date, headline, url, read };
});
for (let i = 0; i < news.length; i++) {
const date = new Date(news[i].date);
if (isNaN(date.getTime())) {
reject(new Error(`Unable to parse date ${date}`));
return;
}
}
resolve(news);
});
});
}
catch (err) {
console.error(err);
return null;
}
}
Fetch API & Async Await
practical demo
const fetchJSON = (url = ``) => {
return fetch(url,
{
method: "GET",
// mode: "no-cors",
mode: "cors",
credentials: "same-origin",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
})
.then(res => res.json())
.then(
(json) => {
return json;
}
)
.catch(err => console.log(`fetch error`, err));
};
// async / await
async function getDatas(url = ``) {
try {
return await fetchJSON(url);
} catch (err) {
console.error("getDatas error:\n", err);
}
}
Promise & error catch
https://zh.javascript.info/promise-error-handling
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/10116652.html
未经授权禁止转载,违者必究!