What are promises in React Native, How is it different from Callbacks?

By | April 23, 2018

Basically saying both are same. But there are some differences.

Lets see what are some of the advantages of Promises.

  • Promises are just a cleaner way for running asynchronous callbacks.
  • Promises also has error catching mechanism which are not in callbacks.
  • Promises are an abstraction for cleaner and better functional code.

What are callbacks?

Callback is a function that is passed to another function as a parameter, and the callback function is called (or executed) inside the otherFunction

Example

  $("#myBtn").click(function() {
  	alert("Button Clicked");
  });
  

They are basically closures.

What are Promises?

Promises takes one argument, a callback with two parameters, resolve and reject. If the call is a sucess call resolve else call reject.

Example

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (// worked) {
    resolve("Sucessfully completed");
  }
  else {
    reject("something went wrong"));
  }
});

You can also use chanining, like if in a synchronous code, you want to do one after another.

Example

getData('data.json').then(function(mydata) {
  return getData(mydata[0]);
}).then(function(mydata0) {
  console.log("Got mydata!", mydata);
})

Promises with Error functions.

getData('data.json').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.log("Failed!", error);
})

Here there are two functions inside the then(), one for success and other for failure.

Promises with catch

getData('data.json').then(function(response) {
  console.log("Success!", response);
}).catch(function(error) {
  console.log("Failed!", error);
})

Not much about catch. Just a sugar for then() method.

All Promises at once

What if we have a chain of functions and we want to process it only when all completes.

Then the code will be like this.

Promise.all(arrayOfPromises).then(function(arrayOfResults) {
  //...
})

Leave a Reply

Your email address will not be published. Required fields are marked *