如何从Promise函数获取数据?跨文件调用异步函数返回undefined问题求助
undefined Hey there! I see the issue with your code—let's get it sorted out quickly.
The Root Cause
Your show function in service.js is an async function, but you're not returning the result of your axios request. When you use await without returning the value, the async function defaults to resolving with undefined, which is why you're seeing that output. Also, mixing await and .then()/.catch()` is a bit redundant and can lead to this kind of oversight.
Fixed Code Options
You have two clean ways to fix this:
Option 1: Use Promise Chaining (without async/await)
Remove the async keyword and return the entire axios Promise chain directly:
const axios = require("../plugins/axios").default; const module = "psm"; exports.show = (payload) => { return axios .get(`/${module}/${payload}`) .then((res) => { // Return the actual data you need return res.data.data; }) .catch((err) => { // Reject the promise with the error response return Promise.reject(err.response); }); };
Option 2: Use Async/Await (cleaner, more readable)
Stick with async/await but use try/catch instead of .then()/.catch() for better flow:
const axios = require("../plugins/axios").default; const module = "psm"; exports.show = async (payload) => { try { const res = await axios.get(`/${module}/${payload}`); // Return the data directly return res.data.data; } catch (err) { // Throw the error response so it can be caught in your file.js throw err.response; } };
Why This Works
In both fixes, we ensure that the show function returns the Promise (or the resolved value of the axios request). When you call psm.show(12).then(...) in file.js, the .then() will now receive the actual res.data.data from your API call instead of undefined.
内容的提问来源于stack exchange,提问作者Jazuly

