- Asyncronous, non blocking function
- Syncronous, blocking 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