Back to articles
Why Promises Are Better Than Callbacks

Why Promises Are Better Than Callbacks

via Dev.to JavaScriptBala Murugan

What is a Callback: A callback is a function that is passed as an argument to another function and executed later. Example: function greet ( name , callback ) { console . log ( " Hello " + name ); callback (); } function sayBye () { console . log ( " Bye! " ); } greet ( " Bala " , sayBye ); Output : Hello Bala Bye ! What is Callback Hell: When callbacks are nested inside other callbacks many times, it becomes hard to read and maintain. This is called Callback Hell. Example: setTimeout (() => { console . log ( " Step 1 " ); setTimeout (() => { console . log ( " Step 2 " ); setTimeout (() => { console . log ( " Step 3 " ); setTimeout (() => { console . log ( " Step 4 " ); }, 1000 ); }, 1000 ); }, 1000 ); }, 1000 ); This code looks like a pyramid shape. This is called Callback Hell or Pyramid of Doom. Problems in Callback Hell: *Hard to read *Hard to debug *Hard to maintain *Error handling is difficult What is a Promise: A Promise is used to handle asynchronous operations in a better way.

Continue reading on Dev.to JavaScript

Opens in a new tab

Read Full Article
6 views

Related Articles