Comparison
Promises
// Import
const {join} = require('path')
const {readdir, stat} = require('fs')
// Using promises
function readdirWithStatsPromise (path) {
const result = {}
return new Promise(function (resolve, reject) {
readdir(path, function (err, files) {
if ( err ) return reject(err)
Promise.all(
files.map((file) => new Promise(function (resolve, reject) {
stat(join(path, file), function (err, stat) {
if ( err ) return reject(err)
result[file] = stat
resolve()
})
}))
).then(() => result).catch(reject)
})
})
}
readdirWithStatsPromise(process.cwd()).then(console.log).catch(console.error)
// Using taskgroup
const {TaskGroup} = require('taskgroup')
function readdirWithStatsTaskGroup (path, next) {
const result = {}
const tasks = new TaskGroup(`fetch files with stats for ${path}`, {concurrency: 0}).done(function (err) {
if ( err ) return next(err)
next(null, result)
})
readdir(path, function (err, files) {
files.forEach(function (file) {
tasks.addTask(`fetch stat for ${file}`, function (complete) {
stat(join(path, file), function (err, stat) {
if ( err ) return complete(err)
result[file] = stat
complete()
})
})
})
tasks.run()
})
}
readdirWithStatsTaskGroup(process.cwd(), function (err, result) {
if ( err ) return console.error(err)
console.log(result)
})
// Using taskgroup, with some cleaning
const {TaskGroup, Task} = require('taskgroup')
function readdirWithStatsTaskGroup (path, next) {
const result = {}
TaskGroup.create({
concurrency: 0,
name: `fetch files with stats for ${path}`,
next: function (err) {
if ( err ) return next(err)
next(null, result)
},
tasks: files.map(function (file) {
return Task.create(`fetch stat for ${file}`, function (complete) {
stat(join(path, file), function (err, stat) {
if ( err ) return complete(err)
result[file] = stat
complete()
})
})
})
}).run()
}
readdirWithStatsTaskGroup(process.cwd(), function (err, result) {
if ( err ) return console.error(err)
console.log(result)
})Async.js
Last updated
Was this helpful?