0

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 !

Ghislain
  • 115
  • 1
  • 5
  • 2
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Sep 19 '18 at 15:23
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Sep 19 '18 at 15:32

1 Answers1

1

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

Martin Renou
  • 424
  • 2
  • 10
  • Thans you're right ! Now that you point that out it seems obvious ! I have to wait for getCustomerId to finish before display. Thanks a lot @martin ! – Ghislain Sep 19 '18 at 15:34