NodeJS 使用异步方法从另一个函数获取信息

v1uwarro  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(149)

我试图从JSON列表(response.data)中获取所有id并将其返回给main函数。但是我如何从另一个具有async方法的函数中获取信息呢?
我不太明白...
下面是我代码:

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();

我得到了这个:

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

我不明白为什么它是“不确定的”,当我做一个等待之前。

bmp9r5qi

bmp9r5qi1#

使用async/await时,不要使用.then()。如果没有回调,return语句实际上将从get_info返回,而不是从.then()回调返回。

async function get_info() {
    const response = await axios({
//  ^^^^^^^^^^^^^^^^^^^^^^
        method: 'get',
        url: 'https://.../api/records',
        headers: {
            'x-api-key': '...'
        },
        params: {}
    });
    var data = JSON.stringify(response.data);
    var data_array = data.split(',');

    var count = 0;
    const list_id = [];

    for (var 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;
//  ^^^^^^
}

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

相关问题