Async Flow Control in Javascript(ES6)

Welcome to another post!

We will be taking a look at an object called the ‘promise’ that was natively introduced with the release of ECMAScript2015 (ES6) that allows us to work asynchronously.

You might have already heard and know of promises, they have been all over the place with Javascript in the last couple of years, and you may think that they were already built into ES5 but they actually weren’t, there was not native promise support in ES5 and you were probably working with polyfills or libraries like jQuery or Que to work with them.

What Are Promises?

Promises are a helper object that enable us to work with asynchronous tasks. They ‘promise’ or guarantee to give us back some data sometime in the future even if the asynchronous task fails, this allows us to continue with the execution of our code while waiting for a response thus increasing performance.

They allow us to escape “callback hell” which is another way of dealing with asynchronous tasks where a number of callbacks are nested within each other but with promises you simply specify what you want to do when some data comes back and then carry on with your code execution. You can also chain promises very conveniently with out having to nest every things hundreds of levels deep like spaghetti code.

That’s the theory of promises so lets have a look at them.

Creating Promises

Lets start by creating the Promise object and discuss the details.

let promise = new Promise(function(resolve, reject){

})

The Promise takes in a function as an input which takes in two parameters ‘resolve’ and ‘reject’, ill come back to what these parameters mean once we finish writing our Promise.

Now in the function body we write whatever asynchronous task we want to perform – this could be querying data from a database or interacting with a remote API.

Because we obviously don’t have a real asynchronous task to perform we will simulate a task which will take some time to complete and for this we will use the ‘setTimeout’ function.

let promise = new Promise(function(resolve, reject){
setTimeout(function(){

}, 2000);
});

The ‘resolve’ and ‘reject’ parameters which depending on the result of the asynchronous, the appropriate function is called and a return value is passed as an argument.

let promise = new Promise(function(resolve, reject){
setTimeout(function(){
if('test_data' === 'test_data')
resolve('Data returned!')
else
reject('Error!')
}, 2000);
});

Here we determine whether or not the asynchronous task completed as expected.

Now we need to decide what to do when the promise is resolved. We can do this by calling the ‘then’ method on the Promise object.

promise.then(function(value){
console.log(value)
}, function(error){
console.log(error);
});

The ‘value’ parameter holds whatever the promise returns. Remember how I said that the ‘resolve’ and ‘reject’ parameters of the promise object determines the result of the task? well this is the data that is passed to the ‘then’ function on our ‘promise’ reference.

In this case the ‘value’ parameter of the ‘then’ function will either hold ‘Data returned!’ or ‘Error’.

Lets have a look at our promise as a whole.

let promise = new Promise(function(resolve, reject){
setTimeout(function(){
if('test_data' === 'test_data')
resolve('Data returned!')// Pass to promise.then
else
reject('Error!')// Pass to promise.then
}, 2000);
});

// Runs when the promise is completed
// 'value' holds the promise' resolve or reject values
promise.then(function(value){
console.log(value)
}, function(error){
console.log(error);
});

If we look at the code above what do you think will be returned to the console window?

……..

The string ‘Data returned!’ will be the output as the conditional in the promise is true, if it were false then ‘Error!’ would be the out put.

So now lets take a step back and look at what we have done so far:

  • Created our Promise object that takes in a function where an asynchronous task is performed
  • While the application is waiting for some value to be returned, we can continue executing code
  • When data is received by the Promise we need to know if it was successful or not by using the ‘resolve’ and ‘reject’ parameters
  • The .then function of the promise is called and takes in a function with the values of ‘resolve’ or ‘reject’ passed in by the promise

That’s the basics of how to handle asynchronous tasks inside Javascript.

I hope you enjoyed this post/tutorial!

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s