1

I'm new to node js. I want to ask how to get data out of ".then" after the query from database?

Refer to my code

When I do console.log(theResult); it is returning as undefined. How can I solve it?

Ganesa Vijayakumar
  • 2,422
  • 5
  • 28
  • 41
  • 1
    Does this answer your question? [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) – VLAZ Nov 01 '19 at 08:42
  • i'm trying to understand it, do you have simple answer ? – Hikkigaya Hachiman Nov 01 '19 at 08:45
  • No, I don't have a simple answer. It's not a simple question, as it requires understanding what async code is. There are several comprehensive answers that describe the nature of asynchronous code and how to handle it in the linked question. – VLAZ Nov 01 '19 at 08:47
  • ohh okay, thank you for the response – Hikkigaya Hachiman Nov 01 '19 at 08:51

1 Answers1

3

You can use the power of async/await in that case and return the value from the function and use it anywhere.

Here your code goes for query which you have to wrap in async function and return the value:

const getValue = async () => {
    return query.yourQueryMethod(conditions)
    .then(data => {
        return data;
    })
    .catch(err => {
        return err;
    });
}

Here the code where you execute your main async function:

const executeQueryAndExtractData = async () => {
    var myData = await getValue();
    console.log ({ myData });
}

// Here you execute the async function
executeQueryAndExtractData();
Krishan Pal
  • 306
  • 1
  • 3