Can't figure this Worker code out; what am I missing?

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 awaits. 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! :slightly_smiling_face:

(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();
}

In the function fetchJson() you must resolve the promise jsonFetch.json() with await.

return await jsonFetch.json()

Or you could also resolve it with then():

return jsonFetch().json().then(r => r)

1 Like

Thanks! That was the solution. I appreciate you commenting or else I might still have overlooked it. :slightly_smiling_face:

Thanks again!