Skip to content

Asynchronous filter returns a Promise object #3133

@patrulea

Description

@patrulea

Operating system

macOS Sonoma 14.2.1

Eleventy

2.0.1

Describe the bug

I’m writing an async filter to fetch the data of a Sanity document based on its ID.
Logging the data in the console works as expected, but trying to render the result within a template doesn’t, as it returns an empty object (Promise { <pending> }).

<code @text="sRef(reference)"></code>
module.exports = eleventyConfig => {
  eleventyConfig.addJavaScriptFunction("sRef", async reference => {
    try {
      const response = await fetch(`https://${process.env.SANITY_STUDIO_PROJECT_ID}.api.sanity.io/v${process.env.SANITY_STUDIO_API_VERSION}/data/query/${process.env.SANITY_STUDIO_DATASET}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${process.env.SANITY_STUDIO_API_TOKEN}`
        },
        body: JSON.stringify({
          query: `*[_id == $referenceId][0]`,
          params: {
            referenceId: reference
          }
        })
      });
      if (!response.ok) {
        throw new Error(`Error fetching data: ${response.statusText}`);
      }
      const data = await response.json();
      return data.result;
    } catch (error) {
      console.error(`Error fetching data from Sanity: ${error.message}`);
      return null;
    }
  })
}

This is a WebC template but I don’t think it’s related to that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions