giovedì 28 novembre 2013

Asyncronous function in Node.js

There are two kind of function in Node.js:
  • Asyncronous, non blocking function 
  • Syncronous, blocking function
The first type, receive a result throw a callback function:

test('x', function(err, data){
}); 

A common mistake that a node.js newbies developer commit is try to return a value from an asyncronous function. The right way to work with asyncronous function is follow example below:
// Method
function query (sQuery, callback){
     var query = connection.query(sQuery);
     query.on('result',function(row){
        callback(null, row);
     });
};

// Implementation
query("select * from test", function(err, result){
    console.log(err || result);
});
It's important to note that asyncronous functions don't return something explicitly (like return x ...), but they set output values through a callback function; in above example callback function sets err (to null) and output value (to row). There are some paradigms to implement asyncronous functions and this link shows some of these

Nessun commento:

Posta un commento