Hello medikoo,
I am wondering what is the best strategy for passing arguments from one asynchronous function to another. I hope the example will clarify my scenario:
Let assume you need to go through all files in a directory and display size of each file.
Without deferred I would do it like that:
fs.readdir(root, function (err, files) {
files.map(function (file) {
return path.join(root, file);
}).forEach(function (file) {
fs.readFile(file, function (err, data) {
if (err) {
console.error(err);
return;
}
console.log('File "%s" size is %d', file, data.length);
});
});
});
Now I would like to achieve the same results with deferred. My code looks like that (node fs functions are promisified):
readdir(root).map(function (file) {
return path.join(root, file);
}).map(function (file) {
return deferred(file, readFile(file));
}).map(function (data) {
console.log('File "%s" size is %d', data[0], data[1].length);
}).done(function () {
console.log("Processing finished!");
}, function (err) {
console.error(err);
});
The problematic line is:
return deferred(file, readFile(file));
It allows me to pass file argument for further processing, but unfortunately in next function I receive an array and need to access it with indexes:
console.log('File "%s" size is %d', data[0], data[1].length);
It looks like a workaround rather than professional way of handling the situation, therefore I would like to ask you if you see any better ways of solving my example? I am sure there are some :)
Kind regards,
Tomasz