Differences between callback and promise in JS

There are lots of ways to write and create asynchronous code in JavaScript, some of them are

  • Callbacks
  • Promises

Callbacks

Callbacks are nothing but a convention name used for JavaScript functions. This is how asynchronous was handled for a long time and now is the old-fashioned classical approach. In a callback, we pass in a function inside an asynchronous call that will execute the call back when the main asynchronous call is done, hence the name being callback

The main disadvantage of this approach occurs when you have multiple chained asynchronous tasks, which requires you to define callback functions within callback functions within callback functions… This is called callback hell, it looks something like this ->

fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})

See the pyramid shape and all the }) at the end? Eek!

Promises

Promises were introduced in ES^(2015), A promise represents the result a asynchronous code would output in the future. They provide a clearer way of writing code and representing sequential steps in asynchronous tasks because even in parallel operations you do need to maintain an order of higher sequence, you can set the value of a variable before using it in some other function. They allow us to write asynchronous code in a way that resembles synchronous code.

callAPI().then(function(response){
	return JSONify()
}).then(function(json){
	return DoSomeTask()
}).then(function(result){
	return showThisResult()
})

Looks quite clean, right? This is one of the major reasons promises are used over callbacks other than that they can be created in one place/file and resolved in a completely different file which allows for breaking down of long code to separate files for better readability and manageability of code.