Home > Mobile >  get info from a another function with an async method
get info from a another function with an async method

Time:12-09

I'm trying to get all id from a JSON list (response.data) and return it to the main function. But how can i get info from a another function with an async method ?

I don't really understand this...

here is my code:

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

and i got this :

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

I don't understand why it's "undefinided" when i do an await before.

CodePudding user response:

When you use async/await, don't use .then(). Without the callback, the return statement will actually return from get_info, not from the .then() callback.

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);
    }
}
  • Related