Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Nodejs and async calls to mysql using sequelize block other users

Nodejs and async calls to mysql using sequelize block other users

Problem

this is my first post here, i hope im doing it right. Im learning nodejs for a proyect i want to do, and im using node to write a web service. i followed a tutorial and got to a working web service, but i had to write the part to connect to the db myself. Problem is, it returns data, but it also blocks everything else. If Query 1 takes 20 seconds, query 2 takes only 3 seconds, and i call query 1 and then query 2, query 2 will only be shown after query 1 is done, blocking all potential users! Here is part of my code, if you need more just ask

This is one of the request handlers, the last 2 params are for testing.

function start(response){
        console.log("Request handler 'insertHood' was called.");
        response.writeHead(200, {"Content-Type": "text/html"});
        var result = db.execute('select x(country_location), y(country_location), country_name, zoom_level from country', response, "Query 1 ", 10);
    }

This is the Function in the database.js file

function execute(query, response, msg, sleepz) {
  var result = sequelize.query(query)
  .success(function(rows)
    {
      sleep(sleepz);
      response.write(msg + JSON.stringify(rows));
      console.log(msg + (new Date()));
      response.end();
    }
  ).error(function(e) {
      console.log("An error occured", e);
      response.write("there was an error man, yo yoy oy");
      response.end();
    }
  );
}

I understand that .success and .error are callback functions, but i cant seem to find a way to make them asynchronous, i read about an async library, but i dont think it does what i need, im sure im doing something wrong, what is it?

Problem courtesy of: Toddy

Solution

Your sleep function is the cause of your problems.

When you create busy wait loops in Node, you effectively stop the ability of Node to process any I/O, like accepting new connections, reading/writing files, querying databases, etc.

If you want to delay sending back a response, you need an asynchronous solution. Fortunately, there is setTimeout:

.success(function(rows) {
  setTimeout(function() {
    response.write(msg + JSON.stringify(rows));
    console.log(msg + (new Date()));
    response.end();
  }, sleepz); // milliseconds
})
Solution courtesy of: robertklep

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Nodejs and async calls to mysql using sequelize block other users

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×