You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Promise函数获取数据?跨文件调用异步函数返回undefined问题求助

Fix: Why Your Function Call Returns 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:54:05