简体   繁体   中英

Issue with node.js loop and db queries

I have to run mysql queries in a loop in Node.js, but what i know it cannot be done in a way I wanned to.
Here is waht I want to achieved:

for(var attributename in body){
   sql.increaseValue(attributename, body[attributename]);
}

I go to parse and JSON object in which i do not number or names of attributes nor its values. I know I need to use some kind of callback pattern. I've read many articles about that but in this case i can't move on
Thanks in advance
Radek

I assume that what you want is to know when all of these operations end? When the loop ends? This can be achieved in multiple ways. I assume that your .increaseValue method accepts a completion callback. If that's the case, then here's a pseudocode:

var finalize = function( ) {
    // for finalization after the loop
};

var requests = [];
for (var attributename in body) {
    (function(attr){
        var req = function() {
            sql.increaseValue( attr, body[ attr ], function( ) {
                var idx = requests.indexOf( req );
                if (idx !== -1) {
                    requests.splice( idx, 1 );
                }
                if (!requests.length) {
                    finalize( );
                }
            } );
        }
        requests.push( req );
    })(attributename);
}

// second loop
for (var i = 0; i < requests.length; i++) {
    requests[i]( );
}

Few things worth noting:

1) If .increaseValue is truely asynchronous, then you can take advantage of the fact that NodeJS is single-threaded and you can get rid of the second loop and simply call req( ) after requests.push( req ); . However if by any chance .increaseValue fires synchronously ( for example when an error occures or something ), then this may cause finalize to fire immediatly. So do this with caution.

2) You need to wrap req definition with an anonymous function because of the scoping.

3) Have a look at caolan's Async.js library . It might help you greatly with this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM