Use async/await

This commit is contained in:
Mimi 2025-07-10 10:56:43 +08:00
parent 5b17f60f6f
commit 55c429d677
16 changed files with 216 additions and 229 deletions

View File

@ -92,13 +92,14 @@
return eventContent; return eventContent;
} }
function fetchData() { async function fetchData() {
const eventList = document.querySelector('.event-list'); const eventList = document.querySelector('.event-list');
if (!eventList) return; if (!eventList) return;
fetch(request_url.href).then(response => { try {
return response.json(); const response = await fetch(request_url.href);
}).then(data => { const data = await response.json();
if (data.items.length === 0) { if (data.items.length === 0) {
eventList.innerHTML = '<hr>'; eventList.innerHTML = '<hr>';
return; return;
@ -127,7 +128,10 @@
eventList.insertAdjacentHTML('beforeend', buildEventDOM(tense, event, start, end)); eventList.insertAdjacentHTML('beforeend', buildEventDOM(tense, event, start, end));
prevEnd = end; prevEnd = end;
}); });
}); } catch (error) {
// eslint-disable-next-line no-console
console.error('Error fetching calendar data:', error);
}
} }
fetchData(); fetchData();

View File

@ -1,8 +1,6 @@
/* global NexT */ /* global NexT */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
NexT.utils.getScript('https://static.addtoany.com/menu/page.js', { condition: window.a2a }) await NexT.utils.getScript('https://static.addtoany.com/menu/page.js', { condition: window.a2a });
.then(() => {
window.a2a.init(); window.a2a.init();
});
}); });

View File

@ -1,6 +1,6 @@
/* global NexT, CONFIG */ /* global NexT, CONFIG */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
const { appid, appkey } = CONFIG.changyan; const { appid, appkey } = CONFIG.changyan;
const mainJs = 'https://cy-cdn.kuaizhan.com/upload/changyan.js'; const mainJs = 'https://cy-cdn.kuaizhan.com/upload/changyan.js';
const countJs = `https://cy-cdn.kuaizhan.com/upload/plugins/plugins.list.count.js?clientId=${appid}`; const countJs = `https://cy-cdn.kuaizhan.com/upload/plugins/plugins.list.count.js?clientId=${appid}`;
@ -17,23 +17,20 @@ document.addEventListener('page:loaded', () => {
// When scroll to comment section // When scroll to comment section
if (CONFIG.page.comments && !CONFIG.page.isHome) { if (CONFIG.page.comments && !CONFIG.page.isHome) {
NexT.utils.loadComments('#SOHUCS') try {
.then(() => { await NexT.utils.loadComments('#SOHUCS');
return NexT.utils.getScript(mainJs, { await NexT.utils.getScript(mainJs, {
attributes: { attributes: {
async: true async: true
} }
}); });
})
.then(() => {
window.changyan.api.config({ window.changyan.api.config({
appid, appid,
conf: appkey conf: appkey
}); });
}) } catch (error) {
.catch(error => {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.error('Failed to load Changyan', error); console.error('Failed to load Changyan', error);
}); }
} }
}); });

View File

@ -1,6 +1,6 @@
/* global NexT, CONFIG, DISQUS */ /* global NexT, CONFIG, DISQUS */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (CONFIG.disqus.count) { if (CONFIG.disqus.count) {
if (window.DISQUSWIDGETS) { if (window.DISQUSWIDGETS) {
@ -24,7 +24,7 @@ document.addEventListener('page:loaded', () => {
this.language = CONFIG.disqus.i18n.disqus; this.language = CONFIG.disqus.i18n.disqus;
} }
}; };
NexT.utils.loadComments('#disqus_thread').then(() => { await NexT.utils.loadComments('#disqus_thread');
if (window.DISQUS) { if (window.DISQUS) {
DISQUS.reset({ DISQUS.reset({
reload: true, reload: true,
@ -35,7 +35,6 @@ document.addEventListener('page:loaded', () => {
attributes: { dataset: { timestamp: '' + +new Date() } } attributes: { dataset: { timestamp: '' + +new Date() } }
}); });
} }
});
} }
}); });

View File

@ -1,11 +1,10 @@
/* global NexT, CONFIG, DisqusJS */ /* global NexT, CONFIG, DisqusJS */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (!CONFIG.page.comments) return; if (!CONFIG.page.comments) return;
NexT.utils.loadComments('#disqus_thread') await NexT.utils.loadComments('#disqus_thread');
.then(() => NexT.utils.getScript(CONFIG.disqusjs.js, { condition: window.DisqusJS })) await NexT.utils.getScript(CONFIG.disqusjs.js, { condition: window.DisqusJS });
.then(() => {
window.dsqjs = new DisqusJS({ window.dsqjs = new DisqusJS({
api : CONFIG.disqusjs.api || 'https://disqus.com/api/', api : CONFIG.disqusjs.api || 'https://disqus.com/api/',
apikey : CONFIG.disqusjs.apikey, apikey : CONFIG.disqusjs.apikey,
@ -15,7 +14,6 @@ document.addEventListener('page:loaded', () => {
title : CONFIG.page.title title : CONFIG.page.title
}); });
window.dsqjs.render(document.querySelector('.disqusjs-container')); window.dsqjs.render(document.querySelector('.disqusjs-container'));
});
}); });
document.addEventListener('pjax:send', () => { document.addEventListener('pjax:send', () => {

View File

@ -1,13 +1,12 @@
/* global NexT, CONFIG, Gitalk */ /* global NexT, CONFIG, Gitalk */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (!CONFIG.page.comments) return; if (!CONFIG.page.comments) return;
NexT.utils.loadComments('.gitalk-container') await NexT.utils.loadComments('.gitalk-container');
.then(() => NexT.utils.getScript(CONFIG.gitalk.js, { await NexT.utils.getScript(CONFIG.gitalk.js, {
condition: window.Gitalk condition: window.Gitalk
})) });
.then(() => {
const gitalk = new Gitalk({ const gitalk = new Gitalk({
clientID : CONFIG.gitalk.client_id, clientID : CONFIG.gitalk.client_id,
clientSecret : CONFIG.gitalk.client_secret, clientSecret : CONFIG.gitalk.client_secret,
@ -20,5 +19,4 @@ document.addEventListener('page:loaded', () => {
distractionFreeMode: CONFIG.gitalk.distraction_free_mode distractionFreeMode: CONFIG.gitalk.distraction_free_mode
}); });
gitalk.render(document.querySelector('.gitalk-container')); gitalk.render(document.querySelector('.gitalk-container'));
});
}); });

View File

@ -1,15 +1,15 @@
/* global NexT, CONFIG */ /* global NexT, CONFIG */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (!CONFIG.page.comments) return; if (!CONFIG.page.comments) return;
NexT.utils.loadComments('#isso-thread') await NexT.utils.loadComments('#isso-thread');
.then(() => NexT.utils.getScript(`${CONFIG.isso}js/embed.min.js`, { await NexT.utils.getScript(`${CONFIG.isso}js/embed.min.js`, {
attributes: { attributes: {
dataset: { dataset: {
isso: `${CONFIG.isso}` isso: `${CONFIG.isso}`
} }
}, },
parentNode: document.querySelector('#isso-thread') parentNode: document.querySelector('#isso-thread')
})); });
}); });

View File

@ -1,9 +1,9 @@
/* global NexT, CONFIG, LivereTower */ /* global NexT, CONFIG, LivereTower */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (!CONFIG.page.comments) return; if (!CONFIG.page.comments) return;
NexT.utils.loadComments('#lv-container').then(() => { await NexT.utils.loadComments('#lv-container');
window.livereOptions = { window.livereOptions = {
refer: CONFIG.page.path.replace(/index\.html$/, '') refer: CONFIG.page.path.replace(/index\.html$/, '')
}; };
@ -15,5 +15,4 @@ document.addEventListener('page:loaded', () => {
async: true async: true
} }
}); });
});
}); });

View File

@ -1,10 +1,10 @@
/* global NexT, CONFIG */ /* global NexT, CONFIG */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (!CONFIG.page.comments) return; if (!CONFIG.page.comments) return;
NexT.utils.loadComments('.utterances-container') await NexT.utils.loadComments('.utterances-container');
.then(() => NexT.utils.getScript('https://utteranc.es/client.js', { await NexT.utils.getScript('https://utteranc.es/client.js', {
attributes: { attributes: {
async : true, async : true,
crossOrigin : 'anonymous', crossOrigin : 'anonymous',
@ -13,5 +13,5 @@ document.addEventListener('page:loaded', () => {
'theme' : CONFIG.utterances.theme 'theme' : CONFIG.utterances.theme
}, },
parentNode: document.querySelector('.utterances-container') parentNode: document.querySelector('.utterances-container')
})); });
}); });

View File

@ -22,7 +22,7 @@ document.addEventListener('DOMContentLoaded', () => {
let isSearching = false; let isSearching = false;
let pendingQuery = null; let pendingQuery = null;
const searchAlgolia = async(searchText, page = 0) => { const searchAlgolia = async (searchText, page = 0) => {
if (isSearching) { if (isSearching) {
pendingQuery = { searchText, page }; pendingQuery = { searchText, page };
return; return;
@ -84,7 +84,7 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}; };
const inputEventFunction = async() => { const inputEventFunction = async () => {
const searchText = input.value.trim(); const searchText = input.value.trim();
if (searchText === '') { if (searchText === '') {
container.innerHTML = '<div class="search-result-icon"><i class="fab fa-algolia fa-5x"></i></div>'; container.innerHTML = '<div class="search-result-icon"><i class="fab fa-algolia fa-5x"></i></div>';

View File

@ -6,9 +6,9 @@ firebase.initializeApp({
}); });
(function() { (function() {
const getCount = (doc, increaseCount) => { const getCount = async (doc, increaseCount) => {
// IncreaseCount will be false when not in article page // IncreaseCount will be false when not in article page
return doc.get().then(d => { const d = await doc.get();
// Has no data, initialize count // Has no data, initialize count
let count = d.exists ? d.data().count : 0; let count = d.exists ? d.data().count : 0;
// If first view this article // If first view this article
@ -20,13 +20,12 @@ firebase.initializeApp({
}); });
} }
return count; return count;
});
}; };
const db = firebase.firestore(); const db = firebase.firestore();
const articles = db.collection(CONFIG.firestore.collection); const articles = db.collection(CONFIG.firestore.collection);
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (CONFIG.page.isPost) { if (CONFIG.page.isPost) {
// Fix issue #118 // Fix issue #118
@ -40,21 +39,19 @@ firebase.initializeApp({
// Mark as visited // Mark as visited
localStorage.setItem(title, true); localStorage.setItem(title, true);
} }
getCount(doc, increaseCount).then(count => { const count = await getCount(doc, increaseCount);
document.querySelector('.firestore-visitors-count').innerText = count; document.querySelector('.firestore-visitors-count').innerText = count;
});
} else if (CONFIG.page.isHome) { } else if (CONFIG.page.isHome) {
const promises = [...document.querySelectorAll('.post-title')].map(element => { const promises = [...document.querySelectorAll('.post-title')].map(element => {
const title = element.textContent.trim(); const title = element.textContent.trim();
const doc = articles.doc(title); const doc = articles.doc(title);
return getCount(doc); return getCount(doc);
}); });
Promise.all(promises).then(counts => { const counts = await Promise.all(promises);
const metas = document.querySelectorAll('.firestore-visitors-count'); const metas = document.querySelectorAll('.firestore-visitors-count');
counts.forEach((val, idx) => { counts.forEach((val, idx) => {
metas[idx].innerText = val; metas[idx].innerText = val;
}); });
});
} }
}); });
})(); })();

View File

@ -7,62 +7,60 @@
return document.getElementById(url).querySelector('.leancloud-visitors-count'); return document.getElementById(url).querySelector('.leancloud-visitors-count');
}; };
const addCount = Counter => { const addCount = async Counter => {
const visitors = document.querySelector('.leancloud_visitors'); const visitors = document.querySelector('.leancloud_visitors');
const url = decodeURI(visitors.id); const url = decodeURI(visitors.id);
const title = visitors.dataset.flagTitle; const title = visitors.dataset.flagTitle;
Counter('get', `/classes/Counter?where=${encodeURIComponent(JSON.stringify({ url }))}`) try {
.then(response => response.json()) const response = await Counter('get', `/classes/Counter?where=${encodeURIComponent(JSON.stringify({ url }))}`);
.then(({ results }) => { const { results } = await response.json();
if (results.length > 0) { if (results.length > 0) {
const counter = results[0]; const counter = results[0];
leancloudSelector(url).innerText = counter.time + 1; leancloudSelector(url).innerText = counter.time + 1;
Counter('put', '/classes/Counter/' + counter.objectId, { try {
await Counter('put', '/classes/Counter/' + counter.objectId, {
time: { time: {
'__op' : 'Increment', '__op' : 'Increment',
'amount': 1 'amount': 1
} }
})
.catch(error => {
console.error('Failed to save visitor count', error);
}); });
} catch (error) {
console.error('Failed to save visitor count', error);
}
} else if (CONFIG.leancloud_visitors.security) { } else if (CONFIG.leancloud_visitors.security) {
leancloudSelector(url).innerText = 'Counter not initialized! More info at console err msg.'; leancloudSelector(url).innerText = 'Counter not initialized! More info at console err msg.';
console.error('ATTENTION! LeanCloud counter has security bug, see how to solve it here: https://github.com/theme-next/hexo-leancloud-counter-security. \n However, you can still use LeanCloud without security, by setting `security` option to `false`.'); console.error('ATTENTION! LeanCloud counter has security bug, see how to solve it here: https://github.com/theme-next/hexo-leancloud-counter-security. \n However, you can still use LeanCloud without security, by setting `security` option to `false`.');
} else { } else {
Counter('post', '/classes/Counter', { title, url, time: 1 }) try {
.then(response => response.json()) const response = await Counter('post', '/classes/Counter', { title, url, time: 1 });
.then(() => { await response.json();
leancloudSelector(url).innerText = 1; leancloudSelector(url).innerText = 1;
}) } catch (error) {
.catch(error => {
console.error('Failed to create', error); console.error('Failed to create', error);
});
} }
}) }
.catch(error => { } catch (error) {
console.error('LeanCloud Counter Error', error); console.error('LeanCloud Counter Error', error);
}); }
}; };
const showTime = Counter => { const showTime = async Counter => {
const visitors = document.querySelectorAll('.leancloud_visitors'); const visitors = document.querySelectorAll('.leancloud_visitors');
const entries = [...visitors].map(element => { const entries = [...visitors].map(element => {
return decodeURI(element.id); return decodeURI(element.id);
}); });
Counter('get', `/classes/Counter?where=${encodeURIComponent(JSON.stringify({ url: { '$in': entries } }))}`) try {
.then(response => response.json()) const response = await Counter('get', `/classes/Counter?where=${encodeURIComponent(JSON.stringify({ url: { '$in': entries } }))}`);
.then(({ results }) => { const { results } = await response.json();
for (const url of entries) { for (const url of entries) {
const target = results.find(item => item.url === url); const target = results.find(item => item.url === url);
leancloudSelector(url).innerText = target ? target.time : 0; leancloudSelector(url).innerText = target ? target.time : 0;
} }
}) } catch (error) {
.catch(error => {
console.error('LeanCloud Counter Error', error); console.error('LeanCloud Counter Error', error);
}); }
}; };
const { app_id, app_key, server_url } = CONFIG.leancloud_visitors; const { app_id, app_key, server_url } = CONFIG.leancloud_visitors;
@ -93,15 +91,17 @@
api_server = `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com`; api_server = `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com`;
} }
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (api_server) { if (api_server) {
fetchData(api_server); fetchData(api_server);
} else { } else {
fetch(`https://app-router.leancloud.cn/2/route?appId=${app_id}`) try {
.then(response => response.json()) const response = await fetch(`https://app-router.leancloud.cn/2/route?appId=${app_id}`);
.then(({ api_server }) => { const { api_server } = await response.json();
fetchData(`https://${api_server}`); fetchData(`https://${api_server}`);
}); } catch (error) {
console.error('Failed to fetch API server', error);
}
} }
}); });
})(); })();

View File

@ -1,11 +1,11 @@
/* global NexT, CONFIG, mermaid */ /* global NexT, CONFIG, mermaid */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
const mermaidElements = document.querySelectorAll('pre > .mermaid'); const mermaidElements = document.querySelectorAll('pre > .mermaid');
if (mermaidElements.length) { if (mermaidElements.length) {
NexT.utils.getScript(CONFIG.mermaid.js, { await NexT.utils.getScript(CONFIG.mermaid.js, {
condition: window.mermaid condition: window.mermaid
}).then(() => { });
mermaidElements.forEach(element => { mermaidElements.forEach(element => {
const box = document.createElement('div'); const box = document.createElement('div');
box.className = 'code-container'; box.className = 'code-container';
@ -27,6 +27,5 @@ document.addEventListener('page:loaded', () => {
sequence : { actorMargin: 50 } sequence : { actorMargin: 50 }
}); });
mermaid.run(); mermaid.run();
});
} }
}); });

View File

@ -1,10 +1,10 @@
/* global NexT, CONFIG, PDFObject */ /* global NexT, CONFIG, PDFObject */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
if (document.querySelectorAll('.pdf-container').length) { if (document.querySelectorAll('.pdf-container').length) {
NexT.utils.getScript(CONFIG.pdf.object_url, { await NexT.utils.getScript(CONFIG.pdf.object_url, {
condition: window.PDFObject condition: window.PDFObject
}).then(() => { });
document.querySelectorAll('.pdf-container').forEach(element => { document.querySelectorAll('.pdf-container').forEach(element => {
PDFObject.embed(element.dataset.target, element, { PDFObject.embed(element.dataset.target, element, {
pdfOpenParams: { pdfOpenParams: {
@ -18,6 +18,5 @@ document.addEventListener('page:loaded', () => {
height : element.dataset.height height : element.dataset.height
}); });
}); });
});
} }
}); });

View File

@ -1,13 +1,11 @@
/* global NexT, CONFIG, WaveDrom */ /* global NexT, CONFIG, WaveDrom */
document.addEventListener('page:loaded', () => { document.addEventListener('page:loaded', async () => {
NexT.utils.getScript(CONFIG.wavedrom.js, { await NexT.utils.getScript(CONFIG.wavedrom.js, {
condition: window.WaveDrom condition: window.WaveDrom
}).then(() => { });
NexT.utils.getScript(CONFIG.wavedrom_skin.js, { await NexT.utils.getScript(CONFIG.wavedrom_skin.js, {
condition: window.WaveSkin condition: window.WaveSkin
}).then(() => { });
WaveDrom.ProcessAll(); WaveDrom.ProcessAll();
});
});
}); });

View File

@ -39,18 +39,19 @@ NexT.utils = {
// One-click copy code support. // One-click copy code support.
target.insertAdjacentHTML('beforeend', '<div class="copy-btn"><i class="fa fa-copy fa-fw"></i></div>'); target.insertAdjacentHTML('beforeend', '<div class="copy-btn"><i class="fa fa-copy fa-fw"></i></div>');
const button = target.querySelector('.copy-btn'); const button = target.querySelector('.copy-btn');
button.addEventListener('click', () => { button.addEventListener('click', async () => {
if (!code) { if (!code) {
const lines = element.querySelector('.code') || element.querySelector('code'); const lines = element.querySelector('.code') || element.querySelector('code');
code = lines.innerText; code = lines.innerText;
} }
if (navigator.clipboard) { if (navigator.clipboard) {
// https://caniuse.com/mdn-api_clipboard_writetext // https://caniuse.com/mdn-api_clipboard_writetext
navigator.clipboard.writeText(code).then(() => { try {
await navigator.clipboard.writeText(code);
button.querySelector('i').className = 'fa fa-check-circle fa-fw'; button.querySelector('i').className = 'fa fa-check-circle fa-fw';
}, () => { } catch {
button.querySelector('i').className = 'fa fa-times-circle fa-fw'; button.querySelector('i').className = 'fa fa-times-circle fa-fw';
}); }
} else { } else {
button.querySelector('i').className = 'fa fa-times-circle fa-fw'; button.querySelector('i').className = 'fa fa-times-circle fa-fw';
} }