search

Home  >  Q&A  >  body text

How to return data from Promise response

<p>How to correctly return data from Promise? I have the following code: </p> <pre class="brush:php;toolbar:false;">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 }) }</pre> <p>However, if I try to use getPageData from the component, I end up with a void function that returns nothing, why? What am I missing here? </p>
P粉988025835P粉988025835483 days ago445

reply all(1)I'll reply

  • P粉426906369

    P粉4269063692023-07-29 00:59:48

    At the very least, your getPageData function itself should be an async function (for clarity of code readability) that will return the Promise returned by the getApiData call.

    For example:


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

    Two further tips:

    You need to parse this Promise to read the data.

    You can decide to do error handling here or higher up in the call hierarchy

    Rule of thumb:

    Async functions are just functions that return a Promise object.

    The actual data will only be returned when the Promise is resolved (using await or .then())

    reply
    0
  • Cancelreply