0
Well, I have a function that returns a value for a callback, but I wanted it to return without that callback, this is possible?
Function in question:
function getProfile(id, fn) {
var sql = "SELECT * FROM profiles WHERE ID in ('" + id + "')";
con.query(sql, function (err, result) {
if (err) throw err;
fn(result[0]);
);
}
Code in place:
var userData = getProfile(123, function(result) {
console.log(result);
});
I wanted the variable userData
didn’t need to callback.
In your example
var userData
you won’t get anything becausegetProfile
profile is asynchronous. You have to useresult
from inside the same callback. It makes sense?– Sergio
I know that but I wanted the userdata variable to have the result[0] of the query results. This is possible?
– Pedro Pinto
Not outside the function. You can do this with functions
async
, new technology that is still being implemented. Visually it looks like what you want but in practice the function pauses and resumes when the value arrives. It’s a matter of taste, there are many different ways to manage asynchronous code. It seems to me you’re resistant to using callbacks because synchronous logic is easier to manage. You have to decide what technology to use and move on. Take a look at this other question I mentioned.– Sergio
I know how it works
async/await
but that wasn’t the point. Because thecon.query()
only have callback, but thanks anyway.– Pedro Pinto
This would only be possible if the database query was synchronous, which goes against the Ode philosophy, where virtually everything involving I/O is asynchronous.
– bfavaretto
@Pedropinto take a look here with logic async/await: https://jsfiddle.net/Sergio_fiddle/g2yfa27v/ Note that the answer comes after 2 seconds
– Sergio
@Sergio I know how it works
async/await
.-.– Pedro Pinto
@Have you seen my jsFiddle? It does exactly what you want, where you have it
var x = funcao();
. That’s not what you wanted?– Sergio
@Sergio n had seen xD obg
– Pedro Pinto