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 !

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.