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:
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.
and here is a great article on Promises is here. Check it out.