此问题在此处已有答案:
How do I return the response from an asynchronous call?(42答案)
17天前关闭。
从Promise返回数据的正确方法是什么?我有以下代码:
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
})
}
字符串
但是如果我试图从一个组件中使用getPageData
,我最终得到一个不返回任何东西的void
函数,为什么?我在这里错过了什么?
1条答案
按热度按时间dxpyg8gm1#
至少,您的
getPageData
函数本身应该是一个async
函数(为了代码可读性的清晰性),它将返回由getApiData
调用返回的promise。例如,在
字符串
另外两个提示:
经验法则:
async
函数只是一个返回Promise
对象的函数。await
或.then()
)。