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

异步函数数据传递问题:async/await获取id列表返回undefined

问题:异步函数返回undefined,无法获取提取的id列表

尝试从API返回的JSON列表(response.data)中提取所有id并返回给main函数,但使用await后仍得到undefined,运行时报错:

PS C:\Users\Enzo\Documents\dev\passerelle>node .\script.js
Hi!
list_id.length on function = 200
C:\Users\Enzo\Documents\dev\passerelle\script.js:84
    console.log("list_id.length = " + list_id.length);
                                              ^

TypeError: Cannot read properties of undefined (reading 'length')
    at main (C:\Users\Enzo\Documents\dev\passerelle\script.js:84:47)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v18.12.1

原代码

var axios = require('axios');

async function get_info() {

    let config = {
        method: 'get',
        url: 'https://.../api/records',
        headers: {
            'x-api-key': '...'
        },
        params: {
        }
    };

    await axios(config)
    .then(function (response) {
        var data = JSON.stringify(response.data);
        var data_array = data.split(',');

        var count = 0;
        const list_id = [];

        for (i = 0; i < data_array.length; i++) { 
            if (data_array[i].includes('"id":')) {
                list_id[count] = data_array[i];
                count++;
            }
        }
        console.log("list_id.length on function = " + list_id.length);
        return list_id;
    })
    .catch(function (error) {
        console.log(error);
    });
}

async function main() {
    console.log("Hi!");
    list_id = await get_info();
    console.log("list_id.length on main = " + list_id.length);
}

main(); 

问题原因

  1. get_info函数无返回值:await axios(...)后的then回调中返回了list_id,但这个返回值属于then的Promise链,并没有被get_info函数返回。get_info函数没有任何return语句,因此默认返回undefined。
  2. 数据处理方式错误:将response.data转成字符串再分割的方式极易出错(比如字段值包含逗号时会破坏结构),response.data本身就是JavaScript对象/数组,可直接操作。

修正后的代码

var axios = require('axios');

async function get_info() {
    let config = {
        method: 'get',
        url: 'https://.../api/records',
        headers: {
            'x-api-key': '...'
        },
        params: {}
    };

    try {
        const response = await axios(config);
        // 假设response.data是包含id字段的对象数组,直接提取id
        const list_id = response.data.map(item => item.id);
        console.log("list_id.length on function = " + list_id.length);
        return list_id;
    } catch (error) {
        console.log(error);
        // 出错时返回空数组,避免main函数拿到undefined
        return [];
    }
}

async function main() {
    console.log("Hi!");
    const list_id = await get_info();
    console.log("list_id.length on main = " + list_id.length);
}

main(); 

修正说明

  • 添加函数返回值:用try/catch替代then/catch,直接返回处理后的list_id,确保get_info函数返回Promise,await能拿到正确结果。
  • 优化数据处理:使用map直接从response.data数组中提取id,逻辑清晰且避免字符串分割的潜在问题。
  • 错误处理优化:catch块中返回空数组,保证main函数始终能拿到可调用.length的数组。

内容的提问来源于stack exchange,提问作者Dreinale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:25:22