I’ve made a Worker that perform website searches. It works great when used with fake data. But it fails when fetching a JSON file with the data to search. (Based on the doc’s fetch JSON example).
For a reason I don’t understand, my fetchJson()
function (see below) returns earlier even though I’m using await
s. Somehow it seems that await
doesn’t wait long enough, if that makes sense.
I’ve spend a lot of time on making this Worker work, but at this point I don’t see my mistakes anymore.
Can you see where I go wrong? Thanks!
(I don’t expect you to fix my code; just mention the name or concept I should use and I’ll take it from there.)
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
const url = new URL(event.request.url);
let platform = getQueryString(url.search, 'p');
let searchQuery = getQueryString(url.search, 's');
return new Response(await search(searchQuery, platform), {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
}
});
}
async function search(query, platform) {
const data = await fetchJson();
// → Error: 'data' is not defined
// ...
}
async function fetchJson() {
let jsonUrl = "https://www.example.com/a/search-index.json";
const jsonFetch = await fetch(jsonUrl, {
headers: {
"content-type": "application/json;charset=UTF-8",
}
});
return jsonFetch.json();
}