Sunday, 15 April 2012

Confusion related to node.js code -



Confusion related to node.js code -

i found code says can run db queries asynchronously

var queries = []; (var i=0;i <1; i++) { queries.push((function(j){ homecoming function(callback) { collection.find( {value:"1"}, function(err_positive, result_positive) { result_positive.count(function(err, count){ console.log("total matches: " + count); positives[j] = count; callback(); }); } ); } })(i)); } async.parallel(queries, function(){ // work results }

i didn't part callback function how defined ? sec in queries.push, passing function(j) j in , (i)

queries.push((function(j){})(i));

i totally confused how code working?

the loop preparing array of nearly-identical functions tasks async.parallel().

after loop, given iterates 1 time currently, queries similar to:

var queries = [ function (callback) { collection.find( // etc. ); } ];

and, each additional iteration, new function (callback) { ... } added.

what callback function how defined ?

callback named argument each of functions. value defined async.parallel() function which, when called, allows async know when each of tasks has completed.

second in queries.push, passing function(j) j in , (i) for

queries.push((function(j){})(i));

the (function(j){})(i) immediately-invoked function look (iife) j named argument, it's called i passed argument, , returns new function (callback) {} pushed onto queries:

queries.push( (function (j) { homecoming function (callback) { // etc. }; })(i) );

the purpose of iife create closure -- lexical scope local variables "stuck" functions defined within scope. allows each function (callback) {} have own j single value of i (since i go on alter value for loop continues).

node.js

No comments:

Post a Comment