Ad

Function Running Before The Outer One?

- 1 answer

I have this server in Node.js using socket.io. I have a function

function updatePoints(){
    pool.getConnection(function(err, connection) {
        connection.query("SELECT * FROM `users`", function(error, rows) {
           //here it fetchs the users' points and emit to their respective sockets
        });
        connection.release();
    });
}

Alright, when I call this function inside another one, it seems to run before the codes that come before it. Here:

function(){
    connection.query('UPDATE `users` SET '...});

    connection.query('UPDATE `users` SET '...});

    updatePoints();
}

This second function is when a user is donating points to another one, so I decrease the points from the donor and increase the receiver's points. Funny thing that when the function is called it emits for the donor just like I want it to do. The donor sees his points updating real time, while in the receiver's side he can't see it, unless the other one donates him points for a second time, then he sees the first donation going on. If the function is running before if should, how can I make it work?

Ad

Answer

connection.query() is asynchronous. That means that calling it just starts the operation and it then runs in the background. Meanwhile, the next line of Javascript runs right away while the connection.query() is going on in the background. So, if you do:

connection.query(...);
someFunction();

Then, as you have discovered, someFunction() will execute before connection.query() finishes.

The solution is to sequence your work using the completion callback of the connection.query() operation by putting anything that should happen after the query completes inside the callback itself.

 connection.query(..., function(err, rows) {
     // execute some function after the query has completed
     someFunction();
 });

This can be extended to more levels like this:

 connection.query(..., function(err, rows) {
     // execute another query after the first one
     connection.query(..., function(err, moreRows) {
         // execute some function after both queries have completed
         someFunction();
     });
 });
 // code placed right here will execute BEFORE the queries finish

Now standard in ES6 and available in many libraries, the concept of promises can also be used to coordinate or synchronize asynchronous operations. You can read more about promises in zillions of places on the web. One introductory explanation is here on MDN.

Ad
source: stackoverflow.com
Ad