-3

What is the correct way to return data from a Promise? I have the following code:

const axios = require("axios").default;

async function getApiData(pathName: string, locale: string) {
    const {axiosRequestUrl} = getApiVars(pathName, locale);

    const axiosClient = axios.create({
        baseURL: process.env.CONTENT_DOMAIN,
        proxy: false
    })

    return await axiosClient.get(axiosRequestUrl);
}

export default function getPageData() {
    getApiData('shared-content', 'en-us')
        .then((data) => {
            return data;
        })
        .catch((error: any) => {
            // log error here
        })
}

but if I try to use getPageData from a component I end up with a void function that does not return anything, why? What I am missing here?

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

1 Answers1

-1

At the very least, your getPageData function should itself be an async function (for clarity in code readability), which would return the promise returned by the getApiData call.

e.g.

export default async function getPageData() {
    return getApiData('shared-content', 'en-us');
}

Two further hints:

  • You will need to resolve this promise in order to read the data.
  • You can decide to do the error handling here on higher in the call hierarchy.

Rules of thumb:

  • an async function is just a function that returns a Promise object.
  • a promise only returns actual data when resolved (with await or .then()).
Andrei
  • 1,723
  • 1
  • 16
  • 27