You could take the following approach:
// add async here to denote the method as awaitable to callers
async function myfunc(){
// Wrap the inner logic with a promise. This allows you
// return a result, when it is available
return new Promise((resolve) => {
con.connect(function(err){
con.query(q,function(err){
// Once the inner functions complete, and
// a result is available, we return that
// result to external code by passing the
// result to the 'resolve' function like
// so:
var result = 'mY Result';
resolve(result)
});
});
})
}
Now depending on how your project is setup, you will usually have two options for how you call myfunc()
:
// Option #1
const queryResultOption1 = await myfunc()
// Option #2
myfunc().then(function(queryResult) {
// Use queryResult here
})
Generally speaking, option #2 is the "older" way of doing things but offers more widespread support, where as option #1 is the "newer" way and tends towards code thats easier to read, reason about and work with, etc.
Update
Note that there are some constraints when using Option #2
. For instance, you can only call the myfunc()
with await
keyword in the context of an async
method.
In other words, this means you can't just call await myfunc()
directly if the place you're calling it from is not denoted async
. So for example, to use this method directly in say, a nodejs entry script, you'd need to do something like this:
(async function () {
const result = await myfunc()
})()
Hope this helps!