You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll look at what promises are and how you can use them to write better JavaScript. Promises are Easier to Read Let's say we want to grab some data from the HipsterJesus API and add it to our page. This API responds with data that looks like this: { "text": "<p>Lorem ipsum...</p>", "params": { "paras": 4, "type": "hipster-latin" } } Using a callback, we'd write something like this: $.getJSON('http://hipsterjesus.com/api/', function(data) { $('body').append(data.text); }); If you're experienced with jQuery, you'll recognize we're making a GET request and expecting JSON in the response body. We're also passing in a callback function that takes the response JSON and adds it to the document. Another way to write this is to use the
Comments (0)
Sign in to post comments.