javascript - Node.js - Argument in an anonymous function without passing it a variable? -


i come c/c++ background , i'm having real trouble trying wrap head around syntax of node.js. anyway, found code online explain difference between blocking , non-blocking code, , it's had me stumped hours. i've tried searching , reading books can't find answer this. example code retrieves user id database.

blocking version:

function getuser(id) {    var user = db.query(id);    return user; }  console.log('name: ' + getuser(432).name); 

non-blocking version (node.js):

function getuser(id, callback) {    db.query(id, callback); }  getuser(432, function (user) {    console.log(user.name); }); 

i'm fine blocking version because in instance, user id assigned variable user. can't seem understand user argument in anonymous function. seems user appears out of , has instructions acted upon it, without relationship existing variable.

how program know user is? how make connection user's id? can't tell if it's lack of knowledge of javascript/node, or whether person wrote code didn't bother complete it. know is, makes no sense in c/c++.

well, you've asked program fetch user, , supplied function accepts argument (or more, depending on library). after operation complete, getuser invoke callback passed result of operation.

here's dummy getuser implementation you:

function getuser(id, callback) {     settimeout(function() {         var result = {id: id, name: "madara"};         callback(result);     }, 1000); // wait second before doing it. asynchronous! }  getuser(42, function(user) { console.log(user); }); 

that function wait 1 second, , invoke callback pass 1 argument, in case, object id passed, , "madara" name.

notice there's nothing blocking getuser, getuser returns immediately, , without waiting callback called.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -