JS中如何存储解析response.data并将数据返回至主函数
问题解决:获取并返回API响应中的ID列表
你的代码存在两个核心问题:一是get_all_id函数没有返回获取到的ID数据,二是main函数没有等待异步请求完成就继续执行,导致请求结果还没返回程序就结束了。以下是修复后的方案:
方案一:使用async/await简化异步逻辑(推荐)
这种写法更直观,符合现代JavaScript异步编程的习惯:
var axios = require('axios'); async function get_all_id() { const config = { method: 'get', url: 'https://.../api/records', headers: { 'x-api-key': 'Secret' }, params: {} }; try { // 用await等待请求完成,直接拿到响应对象 const response = await axios(config); // 提取所有id到数组并返回 return response.data.map(item => item.id); } catch (error) { console.error('请求API失败:', error); throw error; // 抛出错误让调用方处理 } } // 将main改为async函数,等待get_all_id完成 async function main() { console.log("Hi!"); try { const allIds = await get_all_id(); // 打印所有id console.log('获取到的ID列表:'); allIds.forEach(id => console.log(id)); // 这里可以将allIds存储到对象或进行其他处理 const idStore = { ids: allIds }; console.log('存储后的ID对象:', idStore); } catch (error) { console.error('处理ID时出错:', error); } } main();
方案二:保留Promise链式调用写法
如果你更习惯使用.then/.catch的链式写法,也可以这样修改:
var axios = require('axios'); function get_all_id() { const config = { method: 'get', url: 'https://.../api/records', headers: { 'x-api-key': 'Secret' }, params: {} }; // 返回axios请求的Promise,让调用方可以链式处理 return axios(config) .then(response => { return response.data.map(item => item.id); }) .catch(error => { console.error('请求API失败:', error); throw error; }); } function main() { console.log("Hi!"); // 用.then等待请求结果 get_all_id() .then(allIds => { console.log('获取到的ID列表:'); allIds.forEach(id => console.log(id)); // 存储到对象中 const idStore = { ids: allIds }; console.log('存储后的ID对象:', idStore); }) .catch(error => { console.error('处理ID时出错:', error); }); } main();
关键修改点说明
- 返回数据:修改
get_all_id,让它返回提取后的ID数组,而不是只在内部打印,这样main函数才能拿到数据。 - 等待异步操作:
main函数必须等待get_all_id的异步请求完成,要么用await(配合async函数),要么用.then链式调用,否则请求还没返回,程序就已经执行完毕,看不到ID输出。 - 错误处理:保留错误捕获逻辑,确保请求出错时能及时排查问题。
内容的提问来源于stack exchange,提问作者Dreinale
相关产品推荐
相关产品推荐

