Is it possible to return a value within a callback without another callback?

Asked

Viewed 307 times

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 because getProfile profile is asynchronous. You have to use result from inside the same callback. It makes sense?

  • I know that but I wanted the userdata variable to have the result[0] of the query results. This is possible?

  • 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.

  • I know how it works async/await but that wasn’t the point. Because the con.query() only have callback, but thanks anyway.

  • 1

    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.

  • 1

    @Pedropinto take a look here with logic async/await: https://jsfiddle.net/Sergio_fiddle/g2yfa27v/ Note that the answer comes after 2 seconds

  • @Sergio I know how it works async/await .-.

  • @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 n had seen xD obg

Show 4 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.