I want to launch a series of async tasks without using Promise & Async await. My worfklow is : . task 1 . task 2 . task 3 & 4 (in parallel)
I've tried the library async for that. That's ok for a series of sequential task or a series of parallel. But to implement my worklfow, I'm stuck for the moment.
const async = require('async');
const fs = require('fs');
const readFile1 = (name, callback) => {
fs.readFile(name, 'utf-8', (err, data) => {
if (err) {
callback(err);
}
console.log(data);
callback(null, data);
});
}
async.series([
function(callback1) {
async.series([
function(callback1) {
readFile1('./1.txt', callback1);
},
function(callback1) {
readFile1('./2.txt', callback1);
},
], function(err, results) {
console.log('series ', results);
});
},
function(callback2) {
async.parallel([
function(callback2) {
readFile1('./3.txt', callback2);
},
function(callback2) {
readFile1('./4.txt', callback2);
},
], function(err, results) {
console.log('parallel ', results);
});
}
]);
For now only the step 1 & 2 are executed. Have you got an idea for this (apart using a more modern code style with async / await & promises?)
Blured
CodePudding user response:
You need to call the top-level callbacks before async.series()
will continue to the next step:
async.series([
function (callback) {
async.series(
[
function (callback1) {
readFile1("./1.txt", callback1);
},
function (callback2) {
readFile1("./2.txt", callback2);
},
],
function (err, results) {
console.log("series ", results);
return callback(err, results); // <-- here
}
);
},
function (callback) {
async.parallel(
[
function (callback1) {
readFile1("./3.txt", callback1);
},
function (callback2) {
readFile1("./4.txt", callback2);
},
],
function (err, results) {
console.log("parallel ", results);
return callback(err, results); // <-- and here
}
);
},
]);
(renamed callback names to make things a bit more clear)