callback-hell icon indicating copy to clipboard operation
callback-hell copied to clipboard

Can you show what your first example would look like "fixed"?

Open cmoser-edge opened this issue 6 years ago • 2 comments

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.

cmoser-edge avatar Feb 08 '19 14:02 cmoser-edge

I think it's because the most important way to avoid callback hell is not suggested: don't use asynchronous calls everywhere.

adrian-skybaker avatar Apr 09 '21 16:04 adrian-skybaker

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))

lynellf avatar May 13 '22 15:05 lynellf