Saturday, November 24, 2018

What is the difference between callback and promise?

This tutorial we are going to discuss on difference between callback and promise. Nowadays callback and promise widely used in web application development like react js, javascript etc.

What is the difference between callback and promise?

Callback :

A callback is a function that is passed to an another function. A callback may or may not be executed asynchronously. lets see the below example :

function add()
{
    return 234;
}

function ramdom(callback)
{
    // excecuate the code and then call callback function.
    return callback();
}

console.log(ramdom(add));

Output:
--------------------------
> 234

Promise :

A Promise is a object which takes a callback and executes it asynchronously. lets see the below example
var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});

console.log(promise1);
// expected output: [object Promise]

Output:
--------------------------
> [object Promise]
> "foo"

This is all about callback and promise in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment