JavaScript

JavaScript Promises: Creation

In the last post on promises we evaluated how Promises are used. In this post I’ll take a look at how they are created. Here is is how we can create a simple Promise with its asynchronous behavior emulated using the JavaScript setTimeout() function.

Code

We’ll start by requiring Petka Antonov’s bluebird library for our promise implementation shown at 1 below.

Running this code will result in the following output:

Code Review

Let’s review the creation of the the timeoutPromise in depth.

Define the Work

After adding the bluebird library the first thing we did on line 3 was define the doWork() function which is the function which will do the work of the timeoutPromise.

Generate a Delay Length

Next on line 4 we generated a random number and assigned it into the variable timeToSpend. This is the amount of time that we wait to simulate an asynchronous operation. This is comparable to making a remote AJAX or other network call or running a complex database query.

Create the Callback

On line 6 we declare the timeoutCallback() function which we pass to the built in JavaScript function setTimeout() at line 10 along with our timeToSpend variable to specify how long to wait before calling our timeoutCallback() function.

Create the Promise

On line 13 we finally create the timeoutPromise. We use the new operand to invoke the constructor of the Promise object. We pass into the constructor the function which will do the work of the promise, in this case doWork(). We immediately afterwards write out a message to the console to clarify that the promise has not yet resolved.

Write Output to the Console

Then on line 15 we create the function to write out the result of the promise to the console.

Add a Listener

Finally on line 17 we register our printPromiseValue() listener (see JavaScript Promises Explained Part I) printPromiseValue() via the then() method. We immediately afterwards again write out a message to the console to clarify that the promise has still not yet resolved.

Conclusion

Promises are used to simplify and encapsulate asynchronous execution. They help to allow a JavaScript developer to write more readable code and avoid the so-called “callback hell.”

Categories: JavaScript

Tagged as: ,

Leave a Reply

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