Promises – Part 1 – Asynchronous Code

Before I get stuck in to explaining promises, there’s another programming concept I need to go over first; synchronous and asynchronous code. The JavaScript language is asynchronous, which means that it is possible for a block of code to continue running while an asynchronous call is made. Here is a block of JavaScript to help illustrate this concept:

console.log("First");
setTimeout(function() {
    console.log("Second");
}, 200);
console.log("Third");

The output of this code would be:

First
Third
Second

What should come across here is that when the code runs, it does not wait for the setTimeout to finish before executing console.log(“Third”), this is asynchronous code in action!

At first glance this seems a bit dangerous and maybe a bit confusing because it feels like you have less control of how the code executes. In reality though, this allows JavaScript to operate without having to worry about ‘Blocking Functions’.

A Blocking Function is code that will stop the execution of a program until it finishes (also called a synchronous call). This means that if you were performing an AJAX request that was receiving a large amount of data, the request would idle the rest of the program until it had completed, possibly slowing load times. If the call were asynchronous however, the server could continue executing the rest of the program while the AJAX request loaded.

This may have occurred to you while reading the preceding paragraphs, but what if you needed the data back from that AJAX request before you could continue executing the rest of the program? You’d essentially be stuck because your code would fail when it tries to access the data that doesn’t exist yet.

This is exactly where promises come in handy! A promise is a way of asking the code to let you know when an asynchronous process has been completed and then run a different block of code, while still allowing the rest of an application to run.

That’s it for part one which has set the scene for promises and hopefully given you an understanding of asynchronous code and how we can use it. In the next part, I’ll begin looking at callbacks vs promises, ES6 promises and the various JS promise libraries we have at our disposal.

Promises:

Advertisements

3 thoughts on “Promises – Part 1 – Asynchronous Code

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 )

w

Connecting to %s