ES6环境下调用外部JS文件方法返回Undefined问题求助
问题分析
你遇到的核心问题是异步操作的返回值处理逻辑错误。axios.get是异步方法,它返回一个Promise,但你的invokeAgentGetCall方法既没有返回这个Promise,then回调里的return responseBody也只是回调函数自身的返回值,并不是整个invokeAgentGetCall方法的返回值。
所以当你在Test.js里直接打印result.invokeAgentGetCall()时,方法会同步执行完毕(但此时axios请求还在后台处理),自然返回undefined;等到后续请求完成后,才会触发类内部的console.log打印出正确数据。
修复方案
我们需要让invokeAgentGetCall返回Promise,然后在调用时用异步方式获取结果:
第一步:修改AxiosUtils.js,让方法返回Promise
调整方法逻辑,直接返回axios.get的调用结果,同时确保异步结果能传递到外部:
const axios = require('axios'); const https = require('https'); const httpsAgent = new https.Agent({rejectUnauthorized: false}); class TestInvoker { constructor(url, body, hostName, securityContext) { this.url = url; this.body = body; this.hostName = hostName; this.securityContext = securityContext; } invokeAgentGetCall() { // 直接返回axios.get的Promise实例 return axios.get(this.url,{ httpsAgent: httpsAgent, headers:{ "Accept": "application/json", "Content-Type": "application/json", "Hostname": `${this.hostName}`, "prefer":"", "X-AMAZON-SECURITY-CONTEXT": JSON.stringify(this.securityContext), "AMAZON-Request-Id":'', "Access-Control-Allow-Origin": true } }).then((res) => { const responseBody = res.data; console.log('类内部打印:', responseBody); return responseBody; // 这个返回值会被传递到外部的Promise链 }).catch(error => { console.error('请求出错:', error); throw error; // 抛出错误,让外部调用者可以捕获 }) } } module.exports = TestInvoker;
第二步:修改Test.js,用异步方式获取结果
因为invokeAgentGetCall现在返回Promise,你可以选择两种方式处理结果:
方式一:使用async/await(更直观易读)
const TestInvoker = require("./AxiosUtils.js"); // 封装成async函数执行异步逻辑 async function fetchData() { const invoker = new TestInvoker("https://jsonplaceholder.typicode.com/todos/1","","",""); try { const result = await invoker.invokeAgentGetCall(); console.log('外部获取到的结果:', result); } catch (error) { console.error('外部捕获错误:', error); } } fetchData();
方式二:使用then链式调用
const TestInvoker = require("./AxiosUtils.js"); const invoker = new TestInvoker("https://jsonplaceholder.typicode.com/todos/1","","",""); invoker.invokeAgentGetCall() .then(result => { console.log('外部获取到的结果:', result); }) .catch(error => { console.error('外部捕获错误:', error); });
执行效果
现在运行node Test.js,你会先看到类内部打印的响应数据,随后看到外部打印的完整结果,不会再出现undefined的情况。
内容的提问来源于stack exchange,提问作者ArrchanaMohan
相关产品推荐
相关产品推荐

