Ghislain
Ghislain

Reputation: 105

Get undefined when returning a value from an array - Node JS

I'm new to NodeJS and I get some difficulties with its asynchronous nature.

I'm requesting some data using a async function. My second function is used to retrieve an ID while knowing the name (both info are stored in the data returned by the first function).

Everytime I get the 'Found it' in the console, but the return is executed before the loop is over and I get an 'undefined'.

Should I use a callback or use async & await ? Even after lot of research about async & await and callbacks I can't figure a way to make it work !

async function getCustomers() {
        try {
             var customers = await axios({
                //Query parameters
            });
            return customers;
        }
        catch (error) {
            console.log(error);
        }
    }


function getCustomerId(customerName){
        var customerId = null;
        getCustomers().then(function(response){
            for (const  i of response.data){
                console.log(i['name']);

                if(i['name'] == customerName){
                    console.log('Found it !'); //This got displayed in the console
                    customerId = i['id'];
                    return customerId; //This never return the desired value
                    }
                }
            });

    }

console.log(getCustomerId('abcd'));

Thanks for any help provided !

Upvotes: 0

Views: 815

Answers (1)

Martin Renou
Martin Renou

Reputation: 464

You're printing the output of getCustomerId, but it doesn't return anything.

Try returning the Promise with:

return getCustomers().then(function(response) {...});

And then, instead of:

console.log(getCustomerId('abcd'));

You should try:

getCustomerId('abcd').then(function(id) {console.log(id);})

So that you are sure that the Promise is resolved before trying to display its output

Upvotes: 1

Related Questions