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