Я хотів би запропонувати ще одне рішення, яке використовує швидкість та ефективність парадигми програмування в самому ядрі Node: подій.
Все, що ви можете зробити з Обіцянками або модулями, призначеними для управління потоковим контролем, як-от async, можна досягти, використовуючи події та просту стан-машину, яка, на мою думку, пропонує методологію, яку, мабуть, легше зрозуміти, ніж інші варіанти.
Наприклад, припустимо, що ви хочете паралельно підсумовувати довжину декількох файлів:
const EventEmitter = require('events').EventEmitter;
// simple event-driven state machine
const sm = new EventEmitter();
// running state
let context={
tasks: 0, // number of total tasks
active: 0, // number of active tasks
results: [] // task results
};
const next = (result) => { // must be called when each task chain completes
if(result) { // preserve result of task chain
context.results.push(result);
}
// decrement the number of running tasks
context.active -= 1;
// when all tasks complete, trigger done state
if(!context.active) {
sm.emit('done');
}
};
// operational states
// start state - initializes context
sm.on('start', (paths) => {
const len=paths.length;
console.log(`start: beginning processing of ${len} paths`);
context.tasks = len; // total number of tasks
context.active = len; // number of active tasks
sm.emit('forEachPath', paths); // go to next state
});
// start processing of each path
sm.on('forEachPath', (paths)=>{
console.log(`forEachPath: starting ${paths.length} process chains`);
paths.forEach((path) => sm.emit('readPath', path));
});
// read contents from path
sm.on('readPath', (path) => {
console.log(` readPath: ${path}`);
fs.readFile(path,(err,buf) => {
if(err) {
sm.emit('error',err);
return;
}
sm.emit('processContent', buf.toString(), path);
});
});
// compute length of path contents
sm.on('processContent', (str, path) => {
console.log(` processContent: ${path}`);
next(str.length);
});
// when processing is complete
sm.on('done', () => {
const total = context.results.reduce((sum,n) => sum + n);
console.log(`The total of ${context.tasks} files is ${total}`);
});
// error state
sm.on('error', (err) => { throw err; });
// ======================================================
// start processing - ok, let's go
// ======================================================
sm.emit('start', ['file1','file2','file3','file4']);
Що виведе:
початок: початок обробки 4 контурів
forEachPath: запуск 4 технологічних ланцюгів
readPath: file1
readPath: file2
processContent: file1
readPath: файл3
processContent: file2
processContent: file3
readPath: file4
contentContent: file4
Всього 4 файли - 4021
Зауважте, що впорядкування завдань ланцюга технологічного процесу залежить від завантаження системи.
Ви можете передбачити потік програми як:
start -> forEachPath - + -> readPath 1 -> processContent 1 - + -> виконано
+ -> readFile 2 -> processContent 2 - +
+ -> readFile 3 -> processContent 3 - +
+ -> readFile 4 -> processContent 4 - +
Для повторного використання було б тривіально створити модуль для підтримки різних моделей управління потоком, тобто серій, паралельних, пакетних, в той час, поки, і т.д.