What is difference between Callback and Promise in Javascript with example

What is difference between Callback and Promise in Javascript with example

What is difference between Callback and Promise with example

In this Javascript Tutorial, you will learn the basic difference between Callback and Promise with an example.

If you are going to start your career as a Node js developer then you must know about the callback, promises and use of Async and Await to handle deferred operations in JavaScript.

Javascript is a powerful programming language with its ability for closure, callback functions and many other features.

In Javascript, Callback and Promise are two main methods that handle asynchronous tasks.

Callback:

A callback is a function that is passed to an another function and also known as a higher-order function. In another words, when any function accepts another function as an argument then this contained function is called callback function.

Due to event-driven non-blocking I/O model, Node is heavy use of callbacks. A callback may or may not be executed asynchronously.

Example 1:
setInterval(function() {
  console.log('Welcome to ExpertPHP!');
}, 1000);

setInterval accepts a callback function as its first parameter and also a time interval.

Example 2:
function add(val)
{
    return val+1;
}
 
function display(callback)
{    
 
    return callback(2);
}
 
console.log(display(add)); // Result: 3

In the above example, add() is a function and it is passed to function display() as a callback.

Promise:

A promise is an object which is used to handle the asynchronous result of an operation.

The promise constructor takes one argument, a callback function with two parameters, resolve and reject.

let promise = new Promise(function(resolve, reject) {
   // promise description
});

Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only inside the callback function.

  • resolve() — if everything worked successfully then call resolve with result value.
  • reject(error) — if an error occurred then call reject with an error object like throw in plain Javascript.
Example 1:
var flag=true
var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…
 
  if (flag) { 
  /* everything worked successfully */
    resolve("Welcome to ExpertPHP");
  }
  else {
    reject(new Error("Failure"));
  }
});
 
promise
  .then(function(res) {
    // the content from the resolve() is here - Welcome to ExpertPHP
  })
  .catch(function(err) {
    // the error object from the reject() is here - Failure
  });

As compared to Callback function, It is very easy to debug the error with Promise like try-catch block.

A promise made the chaining of functions straightforward and simplified the code. Common need of chaining is to execute two or more asynchronous operations back to back, making it much easier to read. Each subsequent operation starts with the result from the previous step when the previous operation succeeds.

Phone: (+91) 8800417876
Noida, 201301
ataşehir escort maltepe escort bostancı escort kadıköy escort maltepe escort ataşehir escort tuzla escort pendik escort ümraniye escort kartal escort
pendik escort
izmir escort izmir escort izmir escort izmir escort denizli escort antalya escort antalya escort antalya escort izmir escort izmir escort izmir escort izmir escort izmir escort
hatay escort nevsehir escort nigde escort kirikkale escort batman escort osmaniye escort kirklareli escort tokat escort rize escort adiyaman escort gumushane escort batman escort
porno izle
cialis satış cialis fiyat cialis 20 mg cialis 100 mg cialis 5 mg fiyat
sohbet okey oyna
ankara escort marmaris escort bursa escort mersin escort antalya escort izmir escort samsun escort bodrum escort çeşme escort kuşadası escort adana escort eskişehir escort gaziantep escort esenyurt escort pendik escort tuzla escort fatih escort ümraniye escort mecidiyeköy escort kartal escort bahçelievler escort bahçeşehir escort ataşehir escort bakırköy escort nişantaşı escort avcılar escort büyükçekmece escort kurtkoy escort konya escort beşiktaş escort taksim escort beylikdüzü escort malatya escort sakarya escort şişli escort maltepe escort kadıköy escort ataköy escort bostancı escort şirinevler escort bağcılar escort üsküdar escort etiler escort başaksehir escort ortaköy escort kağıthane escort sultangazi escort halkalı escort çekmeköy escort şaşkınbakkal escort mamak escort sincan escort keçiören escort çankaya escort beypazarı escort akyurt escort pursaklar escort kahramankazan escort göztepe escort alsancak escort bornova escort buca escort karabaglar escort karşıyaka escort konak escort narlıdere escort izmit escort başiskele escort kandira escort körfez escort karamürsel escort dilovası escort gölcük escort gebze escort kocaeli escort kayseri escort elazığ escort denizli escort diyarbakir escort adana escort ankara escort izmir escort antalya escort gaziantep escort kayseri escort konya escort mersin escort denizli escort kocaeli escort diyarbakır escort