Node.js chronological issue


I have a problem with node.js. The commands of the program doesn't load cronologically and i don't know how to do it. I'm trying to download some images and text from database and send it with packs of 8. But node.js runs for loop and command after loop at the same time.

Here's my code:

socket.on('background_dinamically', function(data){
        connection.query("SELECT * FROM products WHERE id='"+data.cathegory+"'" , function(err, rows, fields){
            var count = 0;
            var array_elements = [];
                for (var i = rows.length - 1, count; i >= 0; i-- & count ++) {
                    if (count == 8) {
                        socket.emit('image_loading_background', [array_elements, data]);
                        count = 0;
                        array_elements = [];

                if(count > 0 && count < 8 && count != 0) { 
                    socket.emit('image_loading_background', [array_elements, data]);
Problem courtesy of: Marc Ortiz


Marc, first I would check if synchronisation can be done on the client side. If you force your nodejs app to synchronize before sending data to the client, scalability suffers.

If you cannot do without synchronizing on the server side, you can choose between spaghetti code or a sync lib.

Solution courtesy of: asmuelle


Welcome to the world of asynchronous (not chronological) programming. By default, node will work on I/O operations in parallel as you are seeing. To get other behaviors including chronological (in serial), parallel batches, as well as error handling helpers, have a look at one of the many flow control libraries available. Specifically, I recommend caolan/async.

Discussion courtesy of: Peter Lyons

This recipe can be found in it's original form on Stack Over Flow.