I’ve tried to research on how exactly asynchronous functions should be written. After a lot of plowing through a lot of documentation, it’s still unclear to me.
How do I write asynchronous functions for Node? How should I implement error event handling correctly?
Another way to ask my question would be this: How should I interpret the following function?
var async_function = function(val, callback){
process.nextTick(function(){
callback(val);
});
};
Also, I found this question on SO (“How do I create a non-blocking asynchronous function in node.js?”) interesting. I don’t feel like it has been answered yet.
You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.
Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.
Generally API’s give you a callback with an err as the first argument. For example
Is a common pattern.
Another common pattern is
on('error'). For exampleEdit:
The above function when called as
Will print
42to the console asynchronously. In particularprocess.nextTickfires after the current eventloop callstack is empty. That call stack is empty afterasync_functionandconsole.log(43)have run. So we print 43 followed by 42.You should probably do some reading on the event loop.