JavaScript Promises A+ “Anytime, Anywhere”


Screen Shot 2015-01-15 at 5.54.49 PM

Like Vasquez says: “Anytime, Anywhere”

tl;dr: here is the codepen

Expect all network communication to be asynchronous. You don’t know when requests will come back to you, and you likely have no idea what order they will arrive back. So you write your code asynchronously, same as you do in real life:

“Look, just get back to me when it’s done, ok?”

“Sure thing, I’ll call when it’s ready”

That’s all a Promise is – that conversation and that commitment. And they are a great design pattern to restore some sanity to asynchronous code.

It’s a way of restoring a bit of linearity into the process of requesting this, then waiting for it to be done, then doing the next requesting another thing based on that, then waiting for the response. notice all the ‘then’? Promises use that a lot and it’s their most recognizable signature in code:

getMyWebQuery().then(makeAnotherQueryBasedOnthoseResults()).then(collectAllThatAndDisplayIt());

You can’t display the data before both queries are completed, and the second query depends on the first, so Promise design pattern is a way of restoring the dependency in a way that is intuitive to look at in code.

So there is the design pattern, and more recently a design standard called Promises A+ that says just what methods and behaviours libraries using Promises should adhere to. There are libraries that are just to assemble and use promises, like q.js, and there are implementations inside bigger frameworks, like the implementation contained inside the Angular framework.

However there are some non standard implementations like the one in jQuery. It uses a different syntax but the spirit of the design pattern is there. To make it play nicely with other libraries using the standard Promise system, you need to ‘wrap’ the non standard jQuery one.

So that’s the point of this little post: a Codepen example of how to wrap a jQuery asynchronous webservice call in standard Promise notation. The q.js library provides the methods we need to do that, so have a look at the pen and the comments and see if that works for you.

Here is the Codepen example

and here is a great article on Promises is here. Check it out.

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