- Node brings the asynchronous way of writing programs on web browsers into server side.
- Callbacks, or CPS, and event listeners are central devices to achieve that.
- Node implements a core class called Event Emitter, which you can use to create event-driven programs. Ex. A Node HTTP server.
- Most Node built-in functions use callbacks with two arguments: an error and the results.
var fs = require('fs');
fs.readFile('./hoge.txt', function(error, data) {
// ...
}
- You can use Node's event emitter facilities by inheriting the EventEmitter class.
var events = require('events');
var channel = new events.EventEmitter();
- Here is a list of EventEmitter APIs.
- emitter.addListener(event, listener)
- emitter.on(event, listener)
- emitter.once(event, listener)
- emitter.removeListener(event, listener)
- emitter.removeAllListeners([event])
- emitter.setMaxListeners(n)
- emitter.listeners(event)
- emitter.emit(event, [arg1], [arg2], [...])
--Sequencing asynchronous logic
- There are two flow control patterns to orchestrate asynchronous tasks: serial and parallel.
- Serial: executes multiple tasks sequentially.
- Parallel: executes multiple tasks in parallel but proceed to next step after all the tasks were finished.
- A typical way to implement a serial flow control is to create a helper function called next() and use it at the end of each task when it need to pass its result to the next task:
var tasks = {
task1, task2
}
function next(error, result) {
if (error) throw error;
var currentTask = tasks.shift();
if (currentTask) {
currentTask(result);
}
next();
}
function task1 () {
next(null, 'hoge');
}
function task2 (secret) {
next(null, secret + 'piyo');
}
- Here is an example implementation of parallel flow control:
var completedTasks = 0;
var tasks = [];
function checkIfComplete() {
completedTasks++;
if (completedTasks == tasks.length) {
// do something
}
}