I promise, just wait will ya while I do…

A traditional synchronous callback structure versus asynchronous promise equivalent

synchronous

try {
  var value = myFunction();
  console.log(value);
} catch(err) {
  console.log(err);
}

asynchronous

myFunction().then(function(value) {
  console.log(value);
}).catch(function(err) {
  console.log(err);
});

 

In the sync example you would have to wait until myfunction completed before any more code could be executed.  I am sure you have seen sites where the browser UI seems locked up or non-responsive… this kind of code can be the culprit.

The second example returns a promise for the value, then the rest of the code can carry on.  Like rendering a GRID that will hold the data the promise is fetching…  etc…

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s