How to return data from Promise response
P粉988025835
P粉988025835 2023-07-28 10:32:51
0
1
398
<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粉988025835
P粉988025835

reply all(1)
P粉426906369

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!