What is Promise in Javascript?

Image result for promise in javascript

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Used to execute two or more asynchronous operations back to back, 

Start of next is based on previous. 

Can we call it a promise chain?

A promise is a returned object to which you attach callbacks,

Callback means, It will run entirely before the next process run. 

Callbacks will never be called before the completion of the current run of the JavaScript event loop.

Callbacks added with then() even after the success or failure, will be called.

Multiple callbacks may be added by calling then() several times. Each callback is executed one after another, in the order in which they were inserted.

What is the solution?

kindly read the example, its used for what.

Old Way, how we are working.

findCountries(function(country) {
  findStatesOf(country, function(state) {
    findCitiesOf(state, function(city) {
      console.log('finaly got the cities : ' + city);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

Try some new.

findCountries()
.then(function(country) {
  return findStatesOf(country);
})
.then(function(state) {
  return findCitiesOf(state);
})
.then(function(city) {
  console.log('finally got the city: ' + city);
})
.catch(failureCallback);

Next, we will discuss how to use Promise in code.

Posted in Web

Leave a Reply

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