{"id":460,"date":"2016-11-01T12:41:31","date_gmt":"2016-11-01T12:41:31","guid":{"rendered":"https:\/\/mtwoblog.com\/?p=460"},"modified":"2016-11-01T12:41:31","modified_gmt":"2016-11-01T12:41:31","slug":"javascript-promises-meetup-example","status":"publish","type":"post","link":"https:\/\/muhammad.dev\/javascript-promises-meetup-example\/","title":{"rendered":"JavaScript Promises &#8211; a meetup and an example"},"content":{"rendered":"<p>The Colombo JavaScript Meetup group organised an event titled &#8216;<a href=\"https:\/\/www.meetup.com\/Colombo-JS-Meetup\/events\/234772332\/\">JavaScript Promises&#8217;<\/a>\u00a0on 20 October, 2016 at WSO2, Colombo 3.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-461 size-full\" src=\"https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/10\/600_455232009.png?resize=600%2C600&#038;ssl=1\" alt=\"JavaScript Promises\" width=\"600\" height=\"600\" srcset=\"https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/10\/600_455232009.png?w=600&amp;ssl=1 600w, https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/10\/600_455232009.png?resize=300%2C300&amp;ssl=1 300w, https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/10\/600_455232009.png?resize=100%2C100&amp;ssl=1 100w, https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/10\/600_455232009.png?resize=150%2C150&amp;ssl=1 150w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p><!--more-->The two speakers &#8211; Isuru and Raathigeshan were both from Zone 24&#215;7. Below are some of the notes I took from\u00a0the two talks.<\/p>\n<h4>The\u00a0old school way<\/h4>\n<p>Synchronous programming is when the code runs\u00a0statement by statement, only running the following statement when the current one is completed.<\/p>\n<p>Isuru began the talk\u00a0introducing the Synchronous (old school) way of\u00a0coding &#8211; when receiving data from an API endpoint for example. The solution was to\u00a0google and go to stackoverflow only to come back and write a setTimeout().<\/p>\n<p>The\u00a0problem with this approach is that when the synchronous function is huge, this would freeze the application.<\/p>\n<h4>The\u00a0(traditional) Asynchronous way<\/h4>\n<p>Asynchronous JavaScript essentially is when a code is not blocked by something that is to be completed. The page can load and wait for whatever is to\u00a0be received &#8211; maybe some data through an API call. After the return is successful, a callback is made which would typically build the HTML based on the returned data.<\/p>\n<p>Yes, you have achieved non blocking calls. Awesome!<\/p>\n<p>Or is it? While this does ensure an async way of doing things, this way also has a couple of drawbacks:<\/p>\n<ul>\n<li>Callback Hell &#8211; when chaining an absurd number of callback functions. After some time, the code would grow more horizontally than vertically \u00a0&#8211; and that is not a good thing. This problem is also known as The Pyramid of Doom \ud83d\ude42<\/li>\n<li>The stack\/return could be lost, which could throw errors<\/li>\n<li>The callback may execute multiple times<\/li>\n<\/ul>\n<h3>Enter Promises<\/h3>\n<p>The purpose of this blog post is not to lecture you on Promises. There are other awesome ways you can learn about it- <a href=\"https:\/\/developers.google.com\/web\/fundamentals\/getting-started\/primers\/promises\">like this one.<\/a><\/p>\n<p>However, two\u00a0things make promises useful and different from event listeners:<\/p>\n<ul>\n<li>A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.<\/li>\n<li>If a promise has succeeded or failed and you later add a success\/failure callback, the correct callback will be called, even though the event took place earlier.<\/li>\n<\/ul>\n<h3>An example with Promises<\/h3>\n<p>The code below is a simple representation of how Promises can be implemented without any libraries since the current browsers already have support for it.<\/p>\n<p>This works on Google Chrome 54, Mozilla Firefox 49 and Microsoft Edge 38.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/m-muhsin\/9f3b86bf96e059d4c3cbd94d5089b92f.js\"><\/script><\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium_large wp-image-478\" src=\"https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/11\/results.jpg?resize=656%2C254&#038;ssl=1\" alt=\"results\" width=\"656\" height=\"254\" srcset=\"https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/11\/results.jpg?resize=768%2C297&amp;ssl=1 768w, https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/11\/results.jpg?resize=600%2C232&amp;ssl=1 600w, https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/11\/results.jpg?resize=300%2C116&amp;ssl=1 300w, https:\/\/i0.wp.com\/muhammad.dev\/wp-content\/uploads\/2016\/11\/results.jpg?w=979&amp;ssl=1 979w\" sizes=\"auto, (max-width: 656px) 100vw, 656px\" \/><\/p>\n<p>fetch() is a method which is natively supported in modern browsers. It allows us to <a href=\"https:\/\/developers.google.com\/web\/updates\/2015\/03\/introduction-to-fetch\">fetch <\/a>data from API endpoints (duh).<\/p>\n<p>The then() method is called with a promise and it takes two optional arguments &#8211; a success callback and a failure callback.<\/p>\n<p>The catch() block is used to handle errors as you might have guessed it already.<\/p>\n<p>Promises allow chaining &#8211; to link one then method to another &#8211; the return from the previous\u00a0is the argument for the next &#8211; which is a way to condense our code. Combine this with ES6 <a href=\"https:\/\/developer.mozilla.org\/en\/docs\/Web\/JavaScript\/Reference\/Functions\/Arrow_functions\">Arrow functions<\/a> and we have a lot done in a few lines of code.<\/p>\n<p><a href=\"http:\/\/baconipsum.com\/\">baconipsum.com<\/a> has a JSON API REST interface\u00a0for generating meaty lorem ipsum text and can be used by any application. It returns a JSON string array of paragraphs\u00a0and can be\u00a0accessed via https.<\/p>\n<p>In the above example, the fetch method receives the\u00a0result as a response object,<\/p>\n<ul>\n<li>then converts it into an JSON object &#8211; which contains a single array,<\/li>\n<li>then into a\u00a0string &#8211; which\u00a0contains a long string of sentences separated by a period,<\/li>\n<li>then splits the string into an array where there are periods<\/li>\n<li>then prints each item in that array as a list item<\/li>\n<\/ul>\n<p>You can notice that the promise\u00a0gives us a clean way to code subsequent steps &#8211;\u00a0in a story-telling fashion.<\/p>\n<h4>The future &#8211; async\/await<\/h4>\n<p>Lastly, the speakers touched on this new way to do\u00a0what we did in promises. Added in ES7 (ES2016), it is supposed to give us the benefits of synchronous programming when writing code in an asynchronous way, such as the ability to use try\/catch. It\u00a0is supported by Babel and Chrome 55.<\/p>\n<p>I have to understand it myself properly to explain further.\u00a0I hope to try this once I <a href=\"https:\/\/medium.com\/@bluepnume\/learn-about-promises-before-you-start-using-async-await-eb148164a9c8#.ia15jnfld\">fully understand promises<\/a>.<\/p>\n<h4>Conclusion<\/h4>\n<p>In short, the meetup was indeed useful as #CMBJS meetups usually are &#8211; in reigniting our love for JS. This was a blog post I promised myself 12 days ago.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A quick summary and example for using JavaScript Promises<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[8],"tags":[],"class_list":["post-460","post","type-post","status-publish","format-standard","hentry","category-javascript"],"acf":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/posts\/460","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/comments?post=460"}],"version-history":[{"count":0,"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/posts\/460\/revisions"}],"wp:attachment":[{"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/media?parent=460"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/categories?post=460"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/muhammad.dev\/wp-json\/wp\/v2\/tags?post=460"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}