callback-hell
callback-hell copied to clipboard
Can you show what your first example would look like "fixed"?
You showed an example (reading sizes of files) that seems very difficult to make better and even after following your steps, it is tough to read and understand. I would love to see the right way to do that.
I think it's because the most important way to avoid callback hell is not suggested: don't use asynchronous calls everywhere.
You showed an example (reading sizes of files) that seems very difficult to make better and even after following your steps, it is tough to read and understand. I would love to see the right way to do that.
Here's how I'd write it.
function onError(err) {
if (err) {
console.log('Error writing file: ' + err)
}
}
function handleWidths(filename, aspect, resize) {
return function (width, widthIndex) {
var height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
resize(width, height).write(dest + 'w' + width + '_' + filename, onError)
}
}
function handleSize(filename) {
var resize = this.resize
return function (error, values) {
if (error) {
return console.log('Error identifying file size: ' + err)
}
console.log(filename + ' : ' + values)
var aspect = (values.width / values.height)
widths.forEach(handleWidths(filename, aspect, resize))
}
}
function handleFile(gm) {
return function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(handleSize(filename))
}
}
function onRead(gm) {
return function (err, files) {
if (error) {
return console.log("Error finding files: " + error")
}
files.forEach(handleFile(gm))
}
}
fs.readdir(source, onRead(gm))