From 00ff3a75357d295d2f7432888a146954ed9f0b7a Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Sun, 12 May 2024 12:57:41 +0200 Subject: refactor(js): use async/await, it's 2024 --- frontend/static/search.js | 50 ++++++++++++++++++++++------------------------- 1 file changed, 23 insertions(+), 27 deletions(-) (limited to 'frontend/static') diff --git a/frontend/static/search.js b/frontend/static/search.js index a65e10c..15cabe2 100644 --- a/frontend/static/search.js +++ b/frontend/static/search.js @@ -64,34 +64,30 @@ function renderFragmentHTML(html) { } } -function getResults(url) { - fetch(url, { - headers: { - fetch: "true", - }, - }) - .then(async function (res) { - if (res.ok) { - return res.text(); - } else { - throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`); - } - }) - .then(function (html) { - state.fragment = html; - history.pushState(state, null, url); - return renderFragmentHTML(html); - }) - .catch(function (error) { - range.deleteContents(); - range.insertNode(new Text(error.message)); - console.error("fetch failed", error); - }) - .finally(function () { - state.url = url.toJSON(); - state.opened = []; - history.pushState(state, null, url); +async function getResults(url) { + try { + const res = await fetch(url, { + headers: { + fetch: "true", + }, }); + + if (res.ok) { + state.fragment = await res.text(); + history.pushState(state, null, url); + renderFragmentHTML(state.fragment); + } else { + throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`); + } + } catch (error) { + range.deleteContents(); + range.insertNode(new Text(error.message)); + console.error("fetch failed", error); + } finally { + state.url = url.toJSON(); + state.opened = []; + history.pushState(state, null, url); + } } search.addEventListener("submit", function (ev) { -- cgit 1.4.1