<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dart &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/dart/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Sat, 15 Aug 2015 14:12:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>dart &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Sharing CSS Between Polymer Components in Version 1.1 vs 0.5</title>
		<link>https://jessewarden.com/2015/08/sharing-css-between-polymer-components-in-version-1-1-vs-0-5.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sat, 15 Aug 2015 14:12:17 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[components]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[polymer]]></category>
		<category><![CDATA[styling]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4887</guid>

					<description><![CDATA[Finally figured out how to share styles between components in Polymer. In version 0.5 it was &#60;core-style&#62; and in 1.1, they&#8217;ve changed it use shared styles which is pretty easy to grok for someone who sucks at CSS like me. Sadly, the 1.0 docs for Polymer are quite awful. Even more frustrating is most of [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Finally figured out how to <a href="https://blog.polymer-project.org/announcements/2015/08/13/1.1-release/">share styles between components in Polymer</a>. In version 0.5 it was &lt;core-style&gt; and in 1.1, they&#8217;ve changed it use shared styles which is pretty easy to grok for someone who sucks at CSS like me.</p>
<p><span id="more-4887"></span>Sadly, the 1.0 docs for <a href="https://www.polymer-project.org/1.0/docs/start/getting-the-code.html">Polymer</a> are quite awful. Even more frustrating is most of the Google links still point to v0.5 content, including Github repos that don&#8217;t all point to the newer repos. For example, go figure out how to know how to programmatically listen when a <a href="https://elements.polymer-project.org/elements/paper-radio-group">&lt;paper-radio-group&gt;</a> has changed a selected item by the user clicking it&#8230; ready, go. Oh look, you found misery! I reckon this is because they are still trying to keep ahead all of the Web vendor API changes, general code optimizations, and just resource issues. Not sure the size of the Polymer team. On a whim this morning I checked their blog and finally found what I was looking for since I gave up on the documentation (which was quite great in 0.5).</p>
<p>While I primarily work in raw JavaScript all day and sometimes <a href="https://angularjs.org/">Angular</a>, after messing with Polymer for about 2 weeks now, I really really don&#8217;t get the allure of <a href="http://facebook.github.io/react/">React</a>. When I was messing with Angular 2 months ago in <a href="https://www.dartlang.org/">Dart</a> using the new component syntax, it was immediately apparent how quickly you could build UI&#8217;s. It felt like <a href="http://www.adobe.com/products/flex.html">Flex</a>. Just focusing strictly on the UI, not caring about models and controllers and blah blah blah MVC whatever. Just git-r-done.</p>
<p>Polymer feels the same way; I never messed with the Dart version so just doing the JavaScript version, but even so, it&#8217;s a ton like Angular 1.0, just less&#8230; weird. That, and you can include styles WITH your component vs. &#8220;Uh&#8230; Bootstrap will&#8230; like&#8230; handle that somehow. I don&#8217;t know man, go ask the designer, I&#8217;m just the coder.&#8221;</p>
<p>Took me a few weeks to get re-acclimated to <a href="https://www.google.com/design/spec/material-design/introduction.html">Material Design</a>. <a href="http://getbootstrap.com/">Bootstrap</a> provides you with SO many components including general typography out of the box that work quite quickly, whereas Material Design, or even if you start with <a href="http://www.getmdl.io/">Material Design Lite</a>, there&#8217;s still a ton of onus on you to have SOME designer chops, or have a designer as a friend that can help you.</p>
<p>Anyway, glad to know now how to make my CSS styles follow DRY principles.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>JavaScript Transpiled Languages</title>
		<link>https://jessewarden.com/2015/02/javascript-transpiled-languages.html</link>
					<comments>https://jessewarden.com/2015/02/javascript-transpiled-languages.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Mon, 02 Feb 2015 02:15:03 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[6to5]]></category>
		<category><![CDATA[atscript]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[clojurescript]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[compiler]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[ecmascript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[traceur]]></category>
		<category><![CDATA[transpilers]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4751</guid>

					<description><![CDATA[Introduction JavaScript is now the assembly of the web. Rather than wait on language innovation in the design by committee web standards world, many choose to use more advanced languages and tooling to develop in, that then compile to JavaScript. Transpilers, also known as source to source compilers or transcompilers, are used to translates source [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>JavaScript is now the assembly of the web. Rather than wait on language innovation in the design by committee web standards world, many choose to use more advanced languages and tooling to develop in, that then compile to JavaScript.</p>
<p>Transpilers, also known as <a href="http://en.wikipedia.org/wiki/Source-to-source_compiler">source to source compilers</a> or transcompilers, are used to translates source code to another form of source code. They areÂ popular and numerous, not just for JavaScript, but also for C, and many other languages. In this article I cover why they are valuable for JavaScript developers, give details on the popular ones in the community, and go over the use case workflow for each.</p>
<p>I&#8217;ve chosen 6 of the most popular JavaScript transpiled languages used for client web application development:</p>
<ol>
<li><a href="http://jessewarden.com/2015/02/javascript-transpiled-languages.html#coffeescript">CoffeeScript</a></li>
<li><a href="http://jessewarden.com/2015/02/javascript-transpiled-languages.html#typescript">TypeScript</a></li>
<li><a href="http://jessewarden.com/2015/02/javascript-transpiled-languages.html#atscript">AtScript</a></li>
<li><a href="http://jessewarden.com/2015/02/javascript-transpiled-languages.html#clojurescript">ClojureScript</a></li>
<li><a href="http://jessewarden.com/2015/02/javascript-transpiled-languages.html#es6">ES6 to ES5</a></li>
<li><a href="http://jessewarden.com/2015/02/javascript-transpiled-languages.html#dart">Dart</a></li>
</ol>
<p><span id="more-4751"></span></p>
<h2>What</h2>
<p>Transpilers allow you to convert your source code in one language, either 1 file or many, into another language. In JavaScript&#8217;s case, you typically write in 1 language such as CoffeeScript, and using a build system such as <a href="http://gulpjs.com/">Gulp</a> or <a href="http://gruntjs.com/">Grunt</a>, it will compile your .coffee files to .js JavaScript files.Â Most also generate <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">source maps</a> for more streamlinedÂ debugging.</p>
<p>Another use case is the use of annotations where you write comments in the code that have special meaning and reflection API&#8217;s are utilized at runtime to inspect the code&#8217;s meaning and act accordingly. Examples include signifying what type the class is without the need for inheritance which is what AtScript does on top of the TypeScript compiler. Another isÂ describing the static typing contract the function has in JavaScript using the <a href="https://github.com/google/traceur-compiler">Google&#8217;s Traceur</a> compiler. They both will interpret those code comments and generateÂ JavaScript with those special meanings applied.</p>
<h2>Why</h2>
<p>Transpilers in the non-JavaScript past were utilized to convert large code bases to a newer language (such as Python 2 to 3), an old API to a new one, or runtime platform where doing it by hand was impractical and error prone.Â  In the JavaScript world,Â there are a variety of reasons.</p>
<p>The primary reason is that JavaScript innovation is slower than open source and private offerings. It takes a long time to get an ECMAScript feature from committee standard to implemented inÂ all green field browsers. You can use some of those features, and more, in the other languages, today, and still have it run on the standards based, ubiquitous web platform.</p>
<p>Here are few more often cited reasons:</p>
<ol>
<li>JavaScript evolution slow compared to other languages</li>
<li>open source and private languages evolve faster, have more features</li>
<li>sometimes less code</li>
<li>better code</li>
<li>organized code</li>
<li>more language features</li>
<li>leverage existing talent</li>
<li>leverage existing libraries</li>
<li>more efficient runtime</li>
<li>developers are more productive</li>
<li>future proof</li>
<li>clearer code</li>
</ol>
<h2>History</h2>
<p><a href="http://jessewarden.com/wp-content/uploads/2015/02/LLVM-3-0-Officially-Released-bw.png"><img decoding="async" class=" size-thumbnail wp-image-4770 alignleft" src="http://jessewarden.com/wp-content/uploads/2015/02/LLVM-3-0-Officially-Released-bw-150x150.png" alt="LLVM-3-0-Officially-Released bw" width="150" height="150" /></a>Source to source compiling is not a new concept.</p>
<p>In 1981, Digital Research had a program that converted ASM source code for the Intel 8080 processor into A86 source code for the Intel 8086.</p>
<p>In 1983 Cfront was the original compiler for C++ which compiled C++ to C.</p>
<p>In 2000, the <a href="http://llvm.org/">LLVM</a> project was created with a collection of modular and reusable compiler and toolchain technologies. It is used for compiling a variety of of gcc 4.2.1 languages to C. A few of these include Lisp, ActionScript, Ada, D, Fortran, OpenGL, Go, Java, Objective-C, Python, Ruby, C#, and Lua are just a few.</p>
<p>In 2006, Google released Google Web Toolkit, called <a href="http://www.gwtproject.org/">GWT</a>. It enables developers to build cross browser web applications in Java.</p>
<p>Many other source to source compilers have been written forÂ everything to Fortran to Python to either convert an older language to a newer platform, or from an old API to a new one.</p>
<p>Source to source compilers are an old, accepted practice.<br />
<a name="coffeescript"></a></p>
<h2>CoffeeScript</h2>
<h3><a href="http://jessewarden.com/wp-content/uploads/2015/02/coffeescript-logo-bw.png"><img decoding="async" class=" wp-image-4771 size-medium alignnone" src="http://jessewarden.com/wp-content/uploads/2015/02/coffeescript-logo-bw-300x51.png" alt="coffeescript-logo bw" width="300" height="51" srcset="https://jessewarden.com/wp-content/uploads/2015/02/coffeescript-logo-bw-300x51.png 300w, https://jessewarden.com/wp-content/uploads/2015/02/coffeescript-logo-bw.png 450w" sizes="(max-width: 300px) 100vw, 300px" /></a></h3>
<h3>Why</h3>
<p><a href="http://coffeescript.org/">CoffeeScript</a> attempts to expose the good parts of JavaScript and hide the bad parts. Created by the guy responsible for <a href="http://underscorejs.org/">Underscore</a> and <a href="http://backbonejs.org/">Backbone</a>. Benefit is class syntax, fixes JavaScript&#8217;s operators, and has a terse &amp; safe syntax.</p>
<h3>Features</h3>
<ul>
<li>classes with inheritance and super keyword which abstracts away Object.prototype</li>
<li>fixes == equality to work as expected</li>
<li>arrow functions and other shortened initializers for terse code</li>
<li>shortened loop syntax with optimized output and additional keywords</li>
<li>literate coffeescript option which allows code to be written in Markdown</li>
<li>lexical soping of variables (i.e. no need for var keyword)</li>
<li>terse if else then statements, no parentheses or brackets required</li>
<li>rest based parameters</li>
<li>array slice syntax similiar to Python</li>
<li>implied return statement, no need to type it</li>
<li>statements converted to expressions inside closures</li>
<li>uses english for equality operators and compiles down to safe usage</li>
<li>provides existential operator for checking existence of variables</li>
<li>Array/Object destructuring which allows for multiple return values from functions</li>
<li>Function binding for ensuring this scope remains intact</li>
<li>safter switch statements</li>
<li>chained comparrisons</li>
<li>String interpolation</li>
<li>multiline and block strings</li>
<li>Block Regular Expressions (borrows from Perl&#8217;s /x)</li>
</ul>
<h3>Pros</h3>
<ul>
<li>Compiles to nice JavaScript providing good escape hatch if team ends up not liking it</li>
<li>Basically JavaScript, not much to learn</li>
<li>terse code</li>
<li>fixes many of JavaScript&#8217;s basic language problems with safety included</li>
<li>makes classes useable in JavaScript</li>
</ul>
<h3>Cons</h3>
<p>The only con is some developers wish to code only in CoffeeScript, and others do not wish to code in CoffeeScript. These are often quite strong feelings.<br />
<a name="typescript"></a></p>
<h2>TypeScript</h2>
<h3><a href="http://jessewarden.com/wp-content/uploads/2015/02/CRS-56479-bw.png"><img fetchpriority="high" decoding="async" class=" wp-image-4772 size-medium alignnone" src="http://jessewarden.com/wp-content/uploads/2015/02/CRS-56479-bw-300x208.png" alt="CRS-56479-bw" width="300" height="208" srcset="https://jessewarden.com/wp-content/uploads/2015/02/CRS-56479-bw-300x208.png 300w, https://jessewarden.com/wp-content/uploads/2015/02/CRS-56479-bw.png 400w" sizes="(max-width: 300px) 100vw, 300px" /></a></h3>
<h3>Why</h3>
<p><a href="http://www.typescriptlang.org/">TypeScript</a> provides opt-in static typing, class and module syntax, and is based on the ES6 spec. It was created by Anders Hejlsberg of Turbo Pascal, Delphi, and C# fame. Benefit is strong typing with ability to use against 3rd party libraries, package &amp; classes, and backed by Microsoft.</p>
<h3>Features</h3>
<ul>
<li>define strongly typed globals via declare</li>
<li>integrate strong typing to 3rd party libraries via declaration files</li>
<li>strong typing for both built-in primitives, classes, and interfaces</li>
<li>type inference with basic primitives, classes, and interfaces</li>
<li>interfaces can be applied to basic Objects and classes</li>
<li>function literals</li>
<li>class constructor initializers</li>
<li>default parameters</li>
<li>multiple constructor signatures</li>
<li>class inheritance with super keyword</li>
<li>package support via private and public modules</li>
<li>compiler supports generating AMD or CommonJS modules</li>
<li>arrow syntax for function binding</li>
<li>generics</li>
<li>&#8230; and a lot <a href="https://github.com/Microsoft/TypeScript/wiki">more</a>.</li>
</ul>
<h3>Pros</h3>
<ul>
<li>Compiles to nice JavaScript providing good escape hatch if team ends up not liking it</li>
<li>strong typing allows larger projects and teams to find bugs early w/o writing unit tests</li>
<li>classes are made usable in JavaScript with inheritance</li>
<li>Offers package management for classes, unlike CoffeeScript</li>
<li>Like CoffeeScript, a lot of syntactic sugar</li>
</ul>
<h3>Cons</h3>
<p>Typing is not enforced at runtime, only compile time. Also, same problem with CoffeeScript: developers either love or hate it.<br />
<a name="atscript"></a></p>
<h2>AtScript</h2>
<h3><a href="http://jessewarden.com/wp-content/uploads/2015/02/AngularJS_logo.svg-bw.png"><img loading="lazy" decoding="async" class=" wp-image-4773 size-medium alignnone" src="http://jessewarden.com/wp-content/uploads/2015/02/AngularJS_logo.svg-bw-300x80.png" alt="AngularJS_logo.svg bw" width="300" height="80" srcset="https://jessewarden.com/wp-content/uploads/2015/02/AngularJS_logo.svg-bw-300x80.png 300w, https://jessewarden.com/wp-content/uploads/2015/02/AngularJS_logo.svg-bw.png 695w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></h3>
<h3>Why</h3>
<p><a href="https://angularjs.org/">Angular&#8217;s</a> growth in the Enterprise has shown the limits of JavaScript, thus the natural evolution is to a more mature language: TypeScript. However, TypeScript is missing application development features, so the Google Angular team is working with the Microsoft TypeScript team to modify the language &amp; compiler. Specifically class annotations and runtime assertions resulting in an enhanced TypeScript called <a href="https://docs.google.com/document/d/11YUzC-1d0V1-Q3V0fQ7KSit97HnZoKVygDxpWzEYW0U/edit">AtScript</a>.</p>
<h3>Features</h3>
<p>Same as TypeScript. The two additional ones are class metadata annotations and runtime assertions for type safety at runtime. The class metadata annotations are used to denote the Angular component types without having to inherit from a specific class or work within a specific lifecycle API. While it may seem Angular specific, any framework can benefit from class and variable metadata annotations consumed at runtime. <a href="http://aurelia.io/">Aurelia</a> is another MVC framework thatÂ supports AtScript.</p>
<h3>Pros</h3>
<p>All the Pros of TypeScript including:</p>
<ul>
<li>your types being enforced at runtime</li>
<li>can swap out the assertion library with your own</li>
<li>easier &amp; more readable way to declare Angular component types compared Angular 1.0&#8217;s methods</li>
<li>backed by both Google and Microsoft</li>
</ul>
<h3>Cons</h3>
<p>Same as TypeScript, including at the time of his writing, these features are in active development.</p>
<p><a name="clojurescript"></a></p>
<h2>ClojureScript</h2>
<h3><a href="http://jessewarden.com/wp-content/uploads/2015/02/clojure-icon-bw.png"><img loading="lazy" decoding="async" class=" wp-image-4775 size-medium alignnone" src="http://jessewarden.com/wp-content/uploads/2015/02/clojure-icon-bw-300x96.png" alt="clojure-icon-bw" width="300" height="96" srcset="https://jessewarden.com/wp-content/uploads/2015/02/clojure-icon-bw-300x96.png 300w, https://jessewarden.com/wp-content/uploads/2015/02/clojure-icon-bw.png 309w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></h3>
<h3>Why</h3>
<p><a href="http://clojure.org/">Clojure</a> has gained in popularity because it is a functional language that runs on the JVM with concurrency. This same language can be utilized to build client side applications through compilation to JavaScript via the <a href="https://developers.google.com/closure/">Google Closure compiler</a> (note the &#8220;s&#8221; vs. a &#8220;j&#8221;). Touting the same benefits of JavaScript with <a href="http://nodejs.org/">Node</a>, being the same language used on the client and server sharing some of the same libraries.</p>
<h3>Features</h3>
<ul>
<li>functional language, dialect of Lisp</li>
<li>runs on the JVM</li>
<li>supports concurrency written in a synchronous way like Go</li>
<li>optional type hints and type inference to avoid Java reflection</li>
<li>immutable data structures</li>
<li>same language used on the server</li>
</ul>
<h3>Pros</h3>
<ul>
<li>one language for front end and back-end development</li>
<li>supports streams and promises native to the language</li>
<li>immutable data structures are the norm with mutable support enabling easy concurrency with rewind testing support</li>
<li>this makes working with <a href="http://facebook.github.io/react/">React&#8217;s</a> shouldComponentUpdate method insanely efficient and succinct to write</li>
<li>Clojure is a Functional Language</li>
</ul>
<h3>Cons</h3>
<ul>
<li>No popular MVC frameworks ported yet (ie Angular, Backbone, <a href="http://emberjs.com/">Ember</a>). Although one can utilize <a href="https://github.com/purnam/purnam">Purnam</a>, most of these MVC frameworks are OOP based and encourage Clojure Models to be some sort of atom as opposed to being Functional based and using Collections and Streams as the Models.</li>
<li>&#8230; like the Pro, Clojure is a Functional Language</li>
</ul>
<p><a name="es6"></a></p>
<h2>ECMAScript 6 to ECMAScript 5</h2>
<h3><a href="http://jessewarden.com/wp-content/uploads/2015/02/es6-logo-bw.jpg"><img loading="lazy" decoding="async" class=" size-thumbnail wp-image-4776 alignnone" src="http://jessewarden.com/wp-content/uploads/2015/02/es6-logo-bw-150x150.jpg" alt="es6-logo-bw" width="150" height="150" srcset="https://jessewarden.com/wp-content/uploads/2015/02/es6-logo-bw-150x150.jpg 150w, https://jessewarden.com/wp-content/uploads/2015/02/es6-logo-bw.jpg 200w" sizes="auto, (max-width: 150px) 100vw, 150px" /></a></h3>
<h3>Why</h3>
<p>Utilize ECMAScript 6 features of the future, today, while supporting the older browsers of yesterday. Still writing JavaScript, no need to learn a new language. Get a leg up on writing the JavaScript of tomorrow to ensure code bases are easier to modify/reuse in the future. The most common way to do that today is to utilize the <a href="https://6to5.org/">6to5</a> or <a href="https://github.com/google/traceur-compiler">Google Traceur</a> transpilers.</p>
<h3>Features</h3>
<ul>
<li>classes &#8211; no need to agree on an OOP JavaScript pattern or library</li>
<li>modules &#8211; standardized way of organizing code like Java packages</li>
<li>module loading supporting dynamic loading, execution sandbox, and module cache manipulation</li>
<li>private variables</li>
<li>tighter code through arrow functions, object literals</li>
<li>template strings &#8211; safer string creation without a library</li>
<li>destructuring with soft fail pattern matching</li>
<li>constants</li>
<li>iterators like Java and &#8220;for of&#8221;Â support</li>
<li>generators for creating green threads for long running processes</li>
<li>Map, Set, and Weak versions &#8211; updated collection data structures commonly used</li>
<li>Proxy support</li>
<li>Symbols, more powerful Strings for lookups in Maps and Objects</li>
<li>easier to sub-class native classes</li>
<li>various new API&#8217;s to String, Number, Object, and Math</li>
<li>native Promises</li>
<li>reflection api for easier Proxy creation and other higher level tooling</li>
<li>tail calls &#8211; safer recursion</li>
</ul>
<h3>Pros</h3>
<ul>
<li>most ES6 features</li>
<li>team doesn&#8217;t have to learn a new language, it&#8217;s simply JavaScript compiling to JavaScript</li>
<li>you&#8217;re coding the future, today</li>
<li>classes and modules help code quality because of consistency, a core problem in JavaScript applications</li>
<li>module loader helps solve common performance and security issues with JavaScript applications</li>
<li>various features that aren&#8217;t yet implemented are emulated via shims/polyfills that perform well enough</li>
<li>using technology based on web standards ensuring longer term support</li>
</ul>
<h3>Cons</h3>
<ul>
<li>existing JavaScript libraries and frameworks need to be ported, brought into build system, or maintained separately</li>
<li>generators cannot be effectively polyfilled, though polyfills do exist</li>
<li>modules and their loaders do not solve module problem thoroughly&#8230; yet. They are client specific, avoids Common JS, and makes sharing code with Node/io.js challenging. Solution is to use <a href="http://browserify.org/">Browserify</a> and put ES6 classes on module.exports.</li>
<li>most JavaScript coding standards do not yet exist for ES6.</li>
<li>This includes syntax, code quality, and coverage tooling as well.</li>
<li>For many teams not yet used to developing in more enterprise languages (i.e. heavy use of class and module keywords in large codebase), this can be a huge change for them. This is not necessarely the &#8220;safe option&#8221; because &#8220;it&#8217;s just newer, standards based JavaScript&#8221;</li>
</ul>
<p><a name="dart"></a></p>
<h2>Dart</h2>
<h3><a href="http://jessewarden.com/wp-content/uploads/2015/02/dart-logo-wordmarkbw.png"><img loading="lazy" decoding="async" class=" wp-image-4777 size-medium alignnone" src="http://jessewarden.com/wp-content/uploads/2015/02/dart-logo-wordmarkbw-300x80.png" alt="dart-logo-wordmarkbw" width="300" height="80" srcset="https://jessewarden.com/wp-content/uploads/2015/02/dart-logo-wordmarkbw-300x80.png 300w, https://jessewarden.com/wp-content/uploads/2015/02/dart-logo-wordmarkbw-1024x272.png 1024w, https://jessewarden.com/wp-content/uploads/2015/02/dart-logo-wordmarkbw.png 1733w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></h3>
<h3>Why</h3>
<p>For Java developers, a mature OOP language with functional elements on both client and server. For full stack developers using JavaScript frameworks on the client and Node on the server, a better language &amp; compiler for larger scale applications. For gaming developers, much of the same benefits they get with TypeScript, but with more functional elements, cross browser API&#8217;s abstracted for them, with a more powerful compiler to optimize their code. All get a Google run package management system and gain immense runtime speed when code runs in the Dart Virtual Machine. <a href="https://www.dartlang.org/">Dart</a> is the full package.</p>
<h3>Features</h3>
<ul>
<li>Dart language &#8211; like JavaScript, object oriented, optionally strongly typed, generics, classes, packages, libraries, promises, streams, and other functional features including basics like no undefined, and == that works like you&#8217;d expect it to.</li>
<li>Dart SDK &#8211; libraries for client and server, cross browser DOM and other HTML5 API abstractions.</li>
<li>pub &#8211; package management system, much like npm or bower</li>
<li>Dart Editor &#8211; Eclipse based IDE with code hinting, intellisense, and basic refactoring abilities. Includes a GUI on top of pub so you can add/remove dependencies as well as create you own.</li>
<li>Dart VM &#8211; runtime utilizing .dart code to run in a virtual machine for great speed. Currently implemented in Chromium with future plans to bring to Chrome and hopefully implement in other browsers.</li>
<li>dart2js &#8211; advanced compiler that converts dart code to JavaScript. Includes generic and data type optimization, tree shaking, and various metadata/reflection/annotation capabilities. You can optionally leave in runtime assertions for data typing.</li>
</ul>
<h3>Pros</h3>
<ul>
<li>language better suited for larger teams &amp; applications built from scratch specifically for building client and server web applications</li>
<li>mature compiler built with web applications in mind, often generating faster executing JavaScript</li>
<li>Built &amp; run by Google</li>
<li>Core part of the Angular 2.0 build lifecycle</li>
<li>A suite of tools for building web applications</li>
<li>Where Chrome only is an option (kiosks, enterprise networks, etc) Dart VM helps gain fast speed, yet not having to use C/C++ for <a href="https://developer.chrome.com/native-client">Native Client</a> development</li>
<li>same language &amp; libraries used on client and server</li>
<li>easier runtime module creation with retained strong-typing for application optimization (as opposed to custom grunt/gulp builds + <a href="https://github.com/ocombe/ocLazyLoad">ocLazyLoad</a> or <a href="http://requirejs.org/">require.js</a> packaging).</li>
<li>supports debugging directly from an Android device</li>
</ul>
<h3>Cons</h3>
<ul>
<li>Unlike CoffeeScript, TypeScript, ClojureScript, and ES6 to ES5, Dart does not provide an easy escape hatch. The transpiled JavaScript is built for a specific runtime. Thus it is not easy to &#8220;try before you buy&#8221; and thus salvaging your work.</li>
<li>This Dart JavaScript runtime specific code causes challenges when attempting to integrate into existing applications. There is JS interop, however, that allows Dart JavaScript to non-Dart JavaScript communication</li>
</ul>
<h2>Conclusions</h2>
<p><a href="http://jessewarden.com/wp-content/uploads/2015/02/javascript-and-the-good-parts-bw.jpg"><img loading="lazy" decoding="async" class=" wp-image-4778 size-medium alignleft" src="http://jessewarden.com/wp-content/uploads/2015/02/javascript-and-the-good-parts-bw-300x140.jpg" alt="javascript-and-the-good-parts-bw" width="300" height="140" srcset="https://jessewarden.com/wp-content/uploads/2015/02/javascript-and-the-good-parts-bw-300x140.jpg 300w, https://jessewarden.com/wp-content/uploads/2015/02/javascript-and-the-good-parts-bw.jpg 600w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></p>
<p>There are many other<a href="https://github.com/jashkenas/coffeescript/wiki/list-of-languages-that-compile-to-js"> transcompiled languages, platforms, and compilers</a> not covered here. The desire for developers to improve various other parts of JavaScript and customize to their team&#8217;s workflow has resulted in a plethora of choices for teams. While it&#8217;s not always clear which choice is the best for the team, what is clear is that transcompiling is a normal practice in JavaScript development, integrates nicely with most build systems, and will continue to improve.</p>
<h2>Special Thanks</h2>
<p>Thanks to <a href="https://twitter.com/nodename">Alan Shaw</a>Â andÂ <a href="https://twitter.com/danielglauser">Daniel Glauser</a> (hire Daniel) for the impromptu Google Hangouts to give my peers and I the lo down on Clojure. Thanks to <a href="https://twitter.com/swannodette">David Nolen</a> for answering my questions and hooking me up with some good Clojure resources to learn. <a href="http://swannodette.github.io/">His blog</a> is crazy and awesome, btw, encourage you to read even if you&#8217;re a clientÂ dev.Â  Thanks to <a href="https://twitter.com/jhooks">Joel Hooks</a>, <a href="https://twitter.com/robpenner">Robert Penner</a>, and <a href="https://twitter.com/bclinkinbeard">Ben Clinkinbeard</a> for clarifying some some finer points and sharing code. Thanks to beer for helping me get through Clojure training.</p>
<p>Title artwork by <a href="http://www.deviantart.com/art/Zelda-Four-Swords-Adventure-189106010">Ry-Spirit</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2015/02/javascript-transpiled-languages.html/feed</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Message Systems in Programming: Part 7 of 7 &#8211; Conclusions</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-7-of-7-conclusions.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 16:01:59 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4733</guid>

					<description><![CDATA[Conclusions As you can see, each messaging system has pro&#8217;s and con&#8217;s. Also, each can, and often is, used in tandem with each other. They aren&#8217;t always stand alone, and many are used in the same code base. As you better understand the basics of messaging systems, you can more easily make your Object Oriented [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="conclusions"></a></p>
<h2>Conclusions</h2>
<p>As you can see, each messaging system has pro&#8217;s and con&#8217;s. Also, each can, and often is, used in tandem with each other. They aren&#8217;t always stand alone, and many are used in the same code base. As you better understand the basics of messaging systems, you can more easily make your Object Oriented code bases easier to encapsulate. It also makes it easier when using Design Patterns to have disparate parts of the code talk to each other in a flexible way.</p>
<p><span id="more-4733"></span><a name="whywritethisandotherrandomnotes"></a></p>
<h2>Why Write This and Other Random Notes</h2>
<p>For context, the whole reason I wrote this article is I had no idea why Promises were so lauded by JavaScript developers. I also had no clue what Streams were and if they were valuable or not. Coming from Flash and Flex, Events worked just fine as a core messaging system for years. There were a few who used Signals, and a few pumped strangeness across the global, and not well known loaderInfo.sharedEvents.</p>
<p>Many articles online explained what Promises and Streams were, but none explained why they mattered, nor why I should use them over some other system. WHY AM I DOING THIS!? The Stream guys are the worst. They use computer science terminology that&#8217;s extremely obtuse &#038; unapproachable, and they assume these words plastered by themselves is enough to justify their usage. &#8220;The Ancients used Stargates, or course we&#8217;re supposed to use them as well&#8221;.</p>
<p>Before writing this, I didn&#8217;t realize CustomEvent&#8217;s only worked with DOM elements. Polymer&#8217;s done a good job at this via their fire method, no doubt, butâ€¦ wow. Talk about having it rough. Those poor JS devs.</p>
<p>I also didn&#8217;t realize JQuery, to solve the above, gave them callbacks for async programming, and basically introduced the concept of Promises to the JS world. I was in my spoiled world of events that worked in visual components or in data components. What I didn&#8217;t realize was that when it came to orchestration, the JQuery crowd actually had a much easier time of it. Once you have more than 2 async events, you start having to hunt through the code to mentally map what function fires what event and what function handles that. When you start chaining those thingsâ€¦ good luck. With Promises, it&#8217;s all centralized, making the code much easier to read. AS3 is basically like TypeScript or Dart; and thus we were all willing to have more verbose code because of strong typing&#8217;s value. Anything that can help make it less more verbose, like Promises, would of been a god send in some of the larger enterprise code bases I&#8217;ve been thrust into fixing.</p>
<p>Sadly, Flash Player garbage collector worked extremely differently post Flash Player 8, so things like local variables can&#8217;t just magically &#8220;exist&#8221; like they do in JavaScript. This was so deeply ingrained, it made it quite hard for me to &#8220;get&#8221; why Promises actually work, and how to clean them up.</p>
<p>I was also confused why <a href="https://docs.angularjs.org/api/ng/service/$q">Angular&#8217;s $q</a> differed so much from the official <a href="https://github.com/kriskowal/q">Q</a>. I then realized they wrote their own version of it. Some of the more important features, however, of long stack traces would of made many people&#8217;s lives easier. The biggest frustration I&#8217;ve had learning the ins and outs of Promises this year was completely useless stack traces. As as spoiled Flex developer, I&#8217;ve watched Chrome in the past 3 years insanely improve it&#8217;s runtime errors and stack traces. None of which seems to make working with nested Promises that much easier when the developers use anonymous functions everywhere. This has completely changed the way I code Promises in JavaScript if not using a Promise library (most of my work is Angular&#8217;s $q so when creating Promise chains, I avoid anon functions like t3h plague if I can, and try/catch throw like a mofo). </p>
<p>After doing a lot of orchestration in larger code bases from a data perspective, Promises really started to make sense once I started doing the same work in JavaScript. Remember, this was before Node, and all Factory / data orchestration had to be done on the client WITHOUT something like <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html">Cocoa&#8217;s CoreData</a>. Once you put Node into the picture, this gets a TON easier. No matter how complicated the Java/.NET developers make your life, you can get yourself the 1 API call you need, with no parsing, in about 2 hours. That. Is. Hot. Shit.</p>
<p>Now, I still don&#8217;t get Streams on the client beyond gaming, or an improved event system for component frameworks (like Polymer or Angular UI). I&#8217;m attempting to <a href="https://github.com/JesterXL/fun-with-dart-streams">recreate Final Fantasy 6&#8217;s battle system as a research exercise</a>. In doing so, I&#8217;ve played with various Stream facets in Dart as well as Frappe (which works more like Bacon/RX).</p>
<p>Although research is still on going, for client side, Streams are way easier to deal with than Events, GUI or not. It took me 3 months to get comfortable, but once I got it, there&#8217;s basically no going back to Events if it I can help it. I&#8217;m not sure how to resolve that for Polymer as I&#8217;m a huge fan of the project, want to use it, but I&#8217;ve already lived through the world of Events and am over it. One of these days I need to hack into it and see if there&#8217;s an easier way to convert &#8220;fire&#8221; and it&#8217;s ilk to Streams vs. just using the common adapters on top. Implementing pause and cancel is where the real work would be.</p>
<p>It&#8217;d be nice of application frameworks would implement these, such as <a href="http://angular-ui.github.io/bootstrap/">Angular UI</a>. A few hours playing with Polymer&#8217;s ObservableList and you&#8217;ll be hooked. Array&#8217;s are too low level for creating truly dynamic application UI controls.</p>
<p>That said, in the data layer, especially when Node comes into play to support your front end REST API, I don&#8217;t have many disparate async events. The value for Streams beyond the GUI layer doesn&#8217;t seem helpful, and smaller promise chains work fine.</p>
<p>In Node, however, the complete opposite. If I had Node back in my Flex consulting days, things would have been much simpler. Waiting weeks, sometimes never, getting the API&#8217;s to be simpler, moved a ton of technical debt on the client side to compensate for this, with large Facade layers over the data. Orchestrating many different API&#8217;s, often from different servers with different request and response formats is ripe for Streams to make them easier to work with. Even better is that Node is in a language I already know: JavaScript. I can use the same libraries in the same build stack on the same CI server.</p>
<p>And yet, even here I struggle to convince others. My guess is they just haven&#8217;t spent 6 months like I have playing with Streams and Promises simply to write a blog post.</p>
<p>I will say the need for a Stream spec is pretty clear. It makes all the Promise libraries immediately understandable in how they work. You have the exact opposite problem with Streams. Sadly, I don&#8217;t think Streams will catch on as hard as Promises do. Promises solve such a core problem in ajax and only have a small native footprint to code whereas Streams require a TON of things.</p>
<p>First off, most browsers, even nightlies, barely scratch the surface of what RX/Bacon/Dart have for functional array methods. We&#8217;ve seen how long it takes browser vendors to acknowledge their value and add them in natively hence why lodash or underscore still reign supreme in most peoples tool belts.</p>
<p>Second, they rely a common expectation of how Streams work and the consensus, especially on cold vs. hot, and Observables vs. Properties, just ain&#8217;t there either yet. Until that mess settles down, the libraries will be the go-to places to embrace Streams. Well, except in Dart where they are in there out of the box. It&#8217;s still unclear to me in Polymer where Events end and Streams begin. Need more time to play.</p>
<p>One small note, I used a variety of text editors to write this post over the past 6 months. After about 4 pages, even if the most recent version of <a href="https://wordpress.org/">WordPress</a> with the improved single page scrolling, it&#8217;s still brutal and version control is confusing. I tried <a href="http://25.io/mou/">Mou</a>, my current favorite Markdown editor, but after about 10 pages performance quickly went down. I gave a few random text editors for the Mac a try and finally settled on <a href="http://www.literatureandlatte.com/scrivener.php">Scrivener</a>. It&#8217;s not safe with my HTML tags as it keeps upper casing b and pre tags, and breaks hyperlinks with it&#8217;s weird double-quote choice, but I&#8217;m sure it&#8217;s a setting I don&#8217;t know yet. Either way, at nearly 20,000 words, ZERO performance problems. Faster to boot up and use compared to Word for Mac. Props to <a href="https://plus.google.com/+CliffHall/posts">Cliff Hall</a> for the recommendation.</p>
<p><a name="specialthanks"></a></p>
<h2>Special Thanks</h2>
<p>Thanks to <a href="http://joelhooks.com/">Joel Hooks</a>, <a href="https://twitter.com/trxcllnt">Paul Taylor</a>, <a href="https://plus.google.com/+danschultzonline/posts">Dan Schultz</a>, and the <a href="https://plus.google.com/communities/114566943291919232850">Dart community</a> for answering my questions.</p>
<p>Art:</p>
<ul>
<li><a href="http://clementsauve.deviantart.com/art/Ao2-40th-day-Antennas-158537814">Ao2 40th day: Antennas</a></li>
<li><a href="http://2501sodapop.deviantart.com/art/grad-lvl-31526040">grad lvl</a></li>
</ul>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-6-of-7-streams.html" class="btn btn-primary">&lt;&lt; Part 6 &#8211; Streams</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Message Systems in Programming: Part 6 of 7 &#8211; Streams</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-6-of-7-streams.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 16:01:03 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4731</guid>

					<description><![CDATA[Streams Streams are merely Array&#8217;s that emit change events through a callback when items are added to it. That&#8217;s it. People try to make them sound magical, complicated, or like some core savior technique of programming life. They&#8217;re not. They&#8217;ve been around long before me in networking code. They&#8217;re how Github visualizes different branches. They&#8217;re [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="streams"></a></p>
<h2>Streams</h2>
<p>Streams are merely Array&#8217;s that emit change events through a callback when items are added to it.</p>
<p>That&#8217;s it.</p>
<p><span id="more-4731"></span>People try to make them sound magical, complicated, or like some core savior technique of programming life. They&#8217;re not. They&#8217;ve been around long before me in networking code. They&#8217;re how <a href="https://github.com/">Github</a> visualizes different branches. They&#8217;re just Arrays that emit change events to a callback you can filter before you get the event. You don&#8217;t even have to use events; you could just use any value you want. Most implementations also play nice with Promises.</p>
<p>Streams are like Events, except you can use Array methods on them BEFORE the event is given to the callback handler, and listeners can pause further events from being emitted. They take the asynchronous flattening abilities of Promises, the filtering abilities of functional Arrays (think all those Array methods on Underscore), and the 1 to many broadcast abilities of Events. They have a flattening power of their own once you start merging streams together. When used with Promises, you can work around the race conditions much like you do for Events.</p>
<p>As a side note, Node&#8217;s <a href="http://nodejs.org/api/stream.html">current version of Streams</a> at the time of this writing is actually based on EventEmitter.</p>
<p>For example, you&#8217;ll use a command to get the weather in JSON:</p>
<pre lang="dart">String url = 'http://api.openweathermap.org/data/2.5/weather?q=Richmond,VA&units=imperial';
EventStream links = new EventStream(HttpRequest.request(url, responseType: 'json').asStream());
links.listen((data)
{
	print(data.response);
});</pre>
<p>In <a href="https://www.dartlang.org/">Dart</a> using <a href="https://github.com/danschultz/frappe">Frappe</a>, you use listen to hear about when streams fire events. Here&#8217;s <a href="https://github.com/Reactive-Extensions/RxJS">RxJS</a> doing the same thing:</p>
<pre lang="javascript">function getWeather()
{
    return $.get('http://api.openweathermap.org/data/2.5/weather?q=Richmond,VA&units=imperial')
    .promise();
}
var currentWeather = distinct.flatMapLatest(getWeather);
currentWeather.subscribe(function(data)
{
   	console.log(data);
});</pre>
<p>And in <a href="https://github.com/baconjs/bacon.js/">Bacon.js</a>, another rad, and less intimidating, JavaScript Stream library:</p>
<pre lang="javascript">function getWeather()
{
    var promise = $.get('http://api.openweathermap.org/data/2.5/weather?q=Richmond,VA&units=imperial')
    .promise();
    return Bacon.fromPromise(promise);
}
getWeather().onValue(function(data)
{
	console.log(data);
});</pre>
<p>Like addEventListener, you pass in a callback to fire when they happen. Like events, listen will pass in the parameter the Stream emits. While events have the convention to pass events as the single and only parameter, many who are used to smaller promises, or putting streaming code on top of existing promise code, more primitive values along with multiple values may be common, and that&#8217;s ok. JavaScript will work.</p>
<p><A name="stronglytypedstreams"></a></p>
<h3>Strongly Typed Streams</h3>
<p>Dart however will give you compile warnings if you don&#8217;t match the types. If you don&#8217;t use strong-typing and expect a certain type, you&#8217;ll get a runtime exception.</p>
<p>For example, this is good:</p>
<pre lang="dart">StreamController<String> controller = new StreamController<String>();
EventStream<String> nameChanges = new EventStream<String>(controller.stream);
nameChanges.listen((String someName)
{
	print("someName: $someName");
});
controller.add("Jesse");</pre>
<p>This will give you a compiler warning:</p>
<pre lang="dart">StreamController<String> controller = new StreamController<String>();
EventStream<String> nameChanges = new EventStream<String>(controller.stream);
nameChanges.listen((int someName)
{
	print("someName: $someName");
});
controller.add("Jesse");</pre>
<p>And this will compile just fine, yet blow up at runtime:</p>
<pre lang="dart">StreamController<String> controller = new StreamController<String>();
EventStream<String> nameChanges = new EventStream<String>(controller.stream);
nameChanges.listen((someName)
{
	int oldAge = 70 + someName;
	print("oldAge: $oldAge");
});
controller.add("Jesse");
//	Exception: Uncaught Error: type 'String' is not a subtype of type 'num' of 'other'.
//    Stack Trace:
//    #0      int.+ (dart:core-patch/integers.dart:15)</pre>
<p>#inb4HaxeDoesntHaveThisProblem</p>
<p>The strong-typing helps both while coding, when you start merging/piping streams or using Composition. It also helps in helping the compiler create faster JavaScript at runtime. This helps when writing Dart for the client or for the server (just like JavaScript in the client and Node).</p>
<p><A name="streamsbeingdonevsinfinite"></a></p>
<h3>Streams Being &#8216;Done&#8217; vs. Infinite</h3>
<p>If you map your mind to Streams firing multiple times like an event, they are immediately familiar. Here&#8217;s Bacon creating an event stream (a Stream of Events, usually from something that spits out events from addEventListener type deal):</p>
<pre lang="javascript">$('#someButton').asEventStream('click').subscribe(function(mouseEvent)
{
	console.log("mouseEvent:", mouseEvent);
});</pre>
<p>&#8220;JQuery, find me this button hidden in the DOM soup, create a Stream from it&#8217;s click addEventListener, and let my anonymous function know about events as they are added in the Stream, kthxbai!&#8221;</p>
<p>Since Events work very similarly to Streams, most Streaming libraries have these kinds of converters to quickly make them work like Streams, yet retain the original Event interface. Lowers the barrier of entry. </p>
<p><A name="filtering"></a><H3>Filtering</h3>
<p>As previously mentioned unlike Events, you can filter them BEFORE you&#8217;re subscribe/listen function is fired. For example, when designing a game, I only want to know about events where a particular character is ready so I can redraw the UI:</p>
<pre lang="dart">initiativeStream.where((InitiativeEvent event)
{
	return event.type == InitiativeEvent.CHARACTER_READY;
})
.listen((event)
{
	print("character ready: ${event.character}");
});</pre>
<p>You&#8217;ll notice I&#8217;m treating the initiativeStream here as an Array, using a where function. If you&#8217;re not familiar with uber functional Array stuff, check out <a href="http://underscorejs.org/#where">Underscore&#8217;s definition of where</a> or try your hand at the <a href="http://reactive-extensions.github.io/learnrx/">low-level implementations tutorial</a> to understand why you even need or would want this stuff.</p>
<p>What if I didn&#8217;t have filtering abilities? You&#8217;d write crap like this:</p>
<pre lang="dart">initiativeStream.
.listen((event)
{
	if(event.type == InitiativeEvent.CHARACTER_READY)
	{
		print("character ready: ${event.character}");
	}
});</pre>
<p>Bottom line, every time an initiative event is fired, only let me know about the ready events. Cool. However, anyone who has played RPG games know&#8217;s there is one issue with the above; I&#8217;ll hear about the Monster events as well. Again, without functional Array methods:</p>
<pre lang="dart">initiativeStream.
.listen((event)
{
	if(event.character is Player)
	{
		if(event.type == InitiativeEvent.CHARACTER_READY)
		{
			print("character ready: ${event.character}");
		}
	}
});</pre>
<p>Machete don&#8217;t write nested ifs.</p>
<p>With functional Arrays, you can filter on filters. We&#8217;ll ensure it&#8217;s the correct event type, only from Players, and convert it so we get the player out since that&#8217;s all we care about:</p>
<pre lang="dart">initiativeStream.where((InitiativeEvent event)
{
	return event.type == InitiativeEvent.CHARACTER_READY;
})
.where((InitiativeEvent event)
{
	return event.character is Player;
})
.map((InitiativeEvent event)
{
	return event.character;
})
.listen((Player player)
{
	print("player is ready: ${character}");
});</pre>
<p>Good stuff. Remember, though, like events, that listen callback will get called multiple times if more things come into the stream. The docs for the various libraries and runtimes are confusing in that many methods will go &#8220;when the stream is done&#8221;. Done is a strange word because if you never un-listen, is it REALLY done? The whole chain above will get executed if 5 seconds later when another IntiativeEvent is pumped through the system. In implementations like Dart&#8217;s, they actually can emit a &#8216;done&#8217; type of event if you wish to know. However, for UI Streams like the Bacon one I gave above, it&#8217;s never really done because the user could click anytime they want.</p>
<p><A name="mergingandpipingstreams"></a></p>
<h3>Merging and Piping Streams</h3>
<p>Many systems use Streams to link a series of inputs and outputs together with very little code. The most common are string operations on the command line in many Unix systems.</p>
<pre lang="unix">$ ps aux | grep conky | grep -v grep | awk '{print $2}' | xargs kill</pre>
<p>To read that in Jesse Engrish, &#8220;List my running processes, throw that list to a search program called grep, and look for &#8216;conky&#8217; within it, exclude all the lines that don&#8217;t match, use a program called awk to snag out the process ID (called a PID) I need from the string, and throw that PID at xargs kill which will stop the process from running. Notice in this case the pipe is literally a pipe vs. a &#8220;Stream.pipe()&#8221; function. You can imagine what happens if someone starts changing &#8216;conky&#8217; and keeps re-running ps auxâ€¦ continuously streaming pipes in hot action, sucka!</p>
<p>It should be noted that Node <a href="http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options">already has a way to pipe streams together</a> which is more performant and shorter to write:</p>
<pre lang="javascript">var errorsFromClient = getErrorPostStream();
var errorLogFile = fs.createWriteStream('error.log');
errorsFromClient.pipe(errorLogFile);</pre>
<p>You&#8217;ll often &#8220;pipe&#8221; the data from one command to the next, whether manually doing it like I showed, or using the platform/libraries built in pipe command.</p>
<p>Streams can also indicate a &#8220;series of events&#8221;. As previously mentioned, Node.js uses streams much in this fashion using EventEmitters. They&#8217;re basically Events that have start, progress, and stopping points and are called Streams (api in flux at time of this writing).</p>
<p>Finally, Streams can be merged. One use case is when you&#8217;re building an orchestration on the Node server to have 4 API calls be 1 to make the client side code easier to write and not have to worry about authentication &#038; parsing details. Another use case is flattening all the Events on a client that cause the same thing to happen.</p>
<p>For example, you know how when building a login form, either clicking the &#8220;Login&#8221; button will submit the form as well as hitting enter while within the password field? You can merge Streams to make that easier to read. Here&#8217;s a Bacon example:</p>
<pre lang="javascript">var loginButton = $("#loginButton").asEventStream("click");
var loginField = $("#passwordField").asEventStream("click");
var loginStream = loginButton.merge(loginField);
loginStream.onValue(function()
{
	$.post('server.com/login');
});</pre>
<p>The same technique can be used server-side or client side to flatten orchestrations when making many REST API calls. This example first loads the client&#8217;s location using a geoIP service (uses the server vs. navigator.geolocation) to identify the user&#8217;s latitude and longitude, ensures it&#8217;s not called more than every half a second, parses the result into a Point object, loads the weather passing in the latitude and longitude, and ensures the result isn&#8217;t the same as last time, else it ignores it:</p>
<pre lang="dart" line="1">GetLocation locationService = new GetLocation();
EventStream getWeatherFromGeoIP = new EventStream(locationService.asStream())
.debounce(new Duration(milliseconds: 500))
.map((HttpRequest request)
{
	return new Point(request.response.lat, request.response.lon);
})
.asyncMap((Point point)
{
	return getWeather(point.x, point.y);
})
.distinct();
getWeatherFromGeoIP.listen((num weather)
{
	print("It is $weather degrees.");
});

new Timer(new Duration(minutes: 1), ()
{
	locationService.getLocation();
});</pre>
<p>If you didn&#8217;t catch it, check out line #10 (getWeather method) where the Stream supports asynchronous filters as well, specifically Promises. This is also an option where you can use Composition vs. Merging of Streams.</p>
<p>Here&#8217;s another example with a less linear approach where you can see different streams emitting events at different times, in this case, Monsters and Players attacking each other. One is controlled by AI, the other controlled by the user:</p>
<pre lang="dart">EventStream<AttackResult> monsterAttacks = new EventStream(new StreamController<AttackResult>().stream);
EventStream<AttackResult> playerAttacks = new EventStream(new StreamController<AttackResult>().stream);
EventStream<AttackResult> attacks = monsterAttacks.merge(playerAttacks);
attacks.listen((AttackResult result)
{
	textDropper.addTextDrop(result.attackTarget, result.hitValue);
});</pre>
<p>In the case of chat applications which will do a request/response in the background, but a real-time socket when you have the application active, like on your phone with <a href="https://www.hipchat.com/">HipChat</a>. Two different application modes, your data comes out the same:</p>
<pre lang="dart">EventStream<ChatMessage> ajaxStream = new EventStream(new StreamController<ChatMessage>().stream);
EventStream<ChatMessage> socketStream = new EventStream(new StreamController<ChatMessage>().stream);
EventStream<ChatMessage> messages = ChatMessage.merge(socketStream);
messages.listen((ChatMessage message)
{
	querySelector("#chatField").text = message.text;
});</pre>
<p><A name="noteonobservables"></a></p>
<h3>Note On Observables</h3>
<p>While not always mentioned in some Stream API&#8217;s, an Observable is often included when describing Stream API&#8217;s. All they&#8217;re referring to is the Observer pattern applied over an Array, like a Collection. When you do an arrayInstance.push(), there are no change events. No one else knows that the Array changed unless you use a CustomEvent or pub sub to inform others that it changed. Thus, many use the Observer pattern to wrap Array&#8217;s to create Collections; similar API, except you know what changed, where, and how. Backbone&#8217;s <a href="http://backbonejs.org/">Model and Collection classes</a> are perfect examples of this.</p>
<p>Streams, however, represent the data coming into their Array IN ORDER, even when merged streams. This is why all the cray cray Functional Array stuff works on top, no matter how many Streams you use. Now, your listen function may fire only 1 time because your Array/Stream only has 1 data item. As that data &#8220;changes&#8221; however, you&#8217;ll get more events. Hence why they call it an Observable; somewhere deep in the API is the Observer pattern watching a piece of data, usually passed by ref if possible to emulate Promise state encapsulation.</p>
<p>You&#8217;ll also sometimes see <a href="http://www.dartdocs.org/documentation/frappe/0.3.0+1/index.html">Properties</a>. These are sometimes like Observables depending on the library. Other times they&#8217;re like Promises that cache data.</p>
<p>Be aware of the context of Observable. This is one of the reasons Streams are so hard to grok because people often cite Observable in many different ways without defining what the hell it actually is. For example, the RX family calls Streams:</p>
<blockquote><p>RxJS = Observables + Operators + Schedulers.</p></blockquote>
<p>Except it&#8217;s not. That quote form the docs is actually talking about RX, not Streams. You could be easily fooled (I was) to think using a Stream library called RX would be defined as Observers, Operators, and Schedulers.</p>
<p>Streams ARE an Observable. Like the Observer pattern: &#8220;This thing changed, let the world know.&#8221; When you change a Stream, it lets the world know. You use functional Array methods to &#8220;operate&#8221; on that data. Operators == Functional Array Methods. And putting Schedulers there makes it sound like Streams are one third made up of these scheduler things. Except their not. It&#8217;s 1 plugin out of the 11 RX hasâ€¦ and that&#8217;s only for some advanced unit testing/functional testing mojo. Most of us ain&#8217;t going to use that.</p>
<p>If you think of a Stream as an Array that emits events when it changes, and thus is an Observer, you&#8217;ll get it. The 2 diverging extremes are &#8220;the Observable&#8217;s current value&#8221;, I.e. The latest value in the Stream. The other end of the spectrum is what I call them as; the Stream is just an Array of values, and you get them in order; so the Array&#8217;s an Observable. They&#8217;re both not technically correct because some Streaming libraries give you insane ballz control over Observables. Some like Frappe even go the Property route.</p>
<p>This is why specs exist after the innovation love has died down and developers have self-loathing when their toys start to get annoying.</p>
<p><A name="coldvshot"></a></p>
<h3>Cold vs. Hot</h3>
<p>When they start speaking really advanced about &#8220;cold vs. Hot&#8221;, don&#8217;t sweat it. All this means is something is Cold when it doesn&#8217;t dispatch events until someone listens. In a cold stream, if I click the mouse 50 times on a Hot button Stream, none of those Events are actually dispatched on the Stream until someone calls listen/subscribe. If it was a hot stream, she&#8217;d act like Events; the Stream would emit the events even if no one is listening.</p>
<p>Another example is reading text from a file. You won&#8217;t start receiving events for it until someone says, &#8220;Yo, read the this text file, and lemme know each line of text read as an event&#8221;. On demand type stuff like ajax calls, reading serialized data from window.localeStorage, querying a Model/Collection for the first time, etc.</p>
<p>Hot is the opposite, and works like Events; they&#8217;re fired whether anyone&#8217;s listening or not. This is for things that are happening whether you&#8217;re there or not. If you&#8217;re listener is late to the party, he&#8217;ll start getting new events from that point forward. If I click the mouse 50 times on a button Stream, and you only add a listen/subscribe callback after 25th has fired, you&#8217;ll only get 25 Events. Same as if you did 25 mouse clicks, then domElement.addEventListener(&#8220;click&#8221;, mouseCallback), then clicked 25 more times.</p>
<p>Dart streams are hot by default, whereas RX ones are cold unless you explicitly make it hot.</p>
<p><A name="streampros"></a></p>
<h3>Stream Pros</h3>
<p>The core goal with Streams is to reduce the amount of code you have to write, centralize the event handling, and filter the events all with Promise support. They do this by embracing functional Array filter methods, improving upon the Events API, support of Promises, with the ability to merge &#038; pipe streams together.</p>
<p>Promises deal with 1 event, not many. Although you can chain and/or bubble the event forward, it&#8217;s still 1 specific event that starts each part of the chain. Streams deal with many events with many listeners.</p>
<p>Promises usually are a 1 time affair. With their caching, while you can restart the sequence with many Promises in a chain and it&#8217;s a lot faster, it&#8217;s still the same piece of data. Streams on the other hand represent new data each time an event occurs by default unless combined with Promises or Observables/Properties. For cold observables, this helps solve the Event race condition problem by using the fact Streams will not usually post events until someone has subscribed/listened. In the case of many, you can utilize Promises to help.</p>
<p>Most Event mechanisms are synchronous whereas Streams can support asynchronous operations as well, yet like Promises, be written in a synchronous way. While not 100% solving race conditions, it helps. Some API&#8217;s such as Dart&#8217;s provide options allowing the Stream to be synchronous or asynchronous. Event emitters can&#8217;t be paused by default, where in some Stream implementations, its assumed those who are listening to the streams can pause them. This means any consumer, anywhere, can pause the stream without having knowledge of what Stream their pausing, whether that Stream is merged or via Composition. Since you can get multiple instances, you can have multiple people with varying levels of control. With great power comes great responsibility. Those who use Streams are now responsible for managing this subscription. This is an additional instance that you must store and later destroy. Here&#8217;s an RX example:</p>
<pre lang="javascript">var stream = getAStream();
var subscription = stream
  .subscribe(
    function (hotness) {
      console.log('Droppin it: ' + hotness);
    });
subscription.dispose();</pre>
<p>Events make this simpler by just forcing everyone to get the emitter instance, and just manager the listeners directly from the emitter. Except in larger code bases, finding this instance isn&#8217;t so simple. Some frameworks in more dynamic languages will offload the listeners secretly through the Decorator pattern onto those who call addEventListener so that garbage collection can more easily deal with the references.</p>
<p>For larger applications, flattening the complexity with Streams is very similar to flattening a complex architecture through Composition and Facades. The difference with Streams is a common API to do so for both consumption of Events as well as the abilities to wire Streams together. In heavy GUI applications in Flash/Flex, we&#8217;d do this with Events, or some other messaging system like <a href="https://github.com/robertpenner/as3-signals">Signals</a>.</p>
<p>They also scale better than Events in larger systems. As Stream / pub sub / Event systems grow, you start to run into the cognitive load challenge of keep track of all the different Event types and who dispatches them in your head including the data and types of data they contain. The difference with Streams is you have the ability to query both the data/Events you&#8217;re getting and operate on that data, all from a higher level structure. Using CSS classes and a DOM query syntax allows a more flexible UI. You can change &#038; refactor things under the surface API, and the surface API still works. Streams are the same way. No matter what you modify, move around underneath, you can still have flexible queries up top to ensure your data is in the format you need when it arrives. For game developers this may seem like something horrible; deeply nested, disparate structures IN SUPPORT OF allowing disparate parts to flexibly talk to each other.</p>
<p>For applications developers on a deadline with ever changing API&#8217;s across different domains, however, different story. You can quickly see how &#8220;querying&#8221; your data and composing it into something more useful from smaller parts, all in synchronous looking code that has a small line count, sounds hot.</p>
<p>To be clear; this isn&#8217;t a panacea; a large code base still has a heavy cognitive load. Streams just help. Helping is good.</p>
<p>For unit testing purposes, it&#8217;s slightly easier in some cold Streams to write unit tests specifically because many Streams will not dispatch events until the 1st listener is subscribed. Some of this behavior is predictable in some API&#8217;s, thus you can write better tests to ensure the listener actually received and reacted on the API regardless of what transformations it and the data composing went through. This all continues to work regardless of how many Streams you merge.</p>
<p><A name="streamcons"></a></p>
<h3>Stream Cons</h3>
<p>There is no spec right now. As such, they are quite confusing to learn. This also inadvertently makes them quite intimidating. Unless you have a game development, animation, or networking hardware background, visualizing how streams scale in larger systems can be quite hard. Bottom line, the lack of a spec means a lack of consensus on how these things are implemented. That&#8217;s really the only valid con for Streams, right now. Everything below is just nitpicking. </p>
<p>Streams also assume you already have good experience with Functional Array programming, and can answer why you&#8217;d use a map, where, and zip on the same Arrayâ€¦ yet applied to Events. Wait, what? If you don&#8217;t, it can be hard to extricate what is part of a Stream, and what&#8217;s part of the library. You have to &#8220;get&#8221; why <a href="https://lodash.com/">lodash</a>/underscore are awesome libraries first before you can see how they can &#8220;improve&#8221; events.</p>
<p>Many also assume you already are comfortable with Promises. Many developers are comfortable with Promises, but still create nested Promise chains vs. flattening them. Most Streaming libraries embrace Promises to make dealing with asynchronous code in a multitude of events easier. This can be a real mind-bender. It takes time to get used to coding this way. If your teammates don&#8217;t, they&#8217;ll get mad when they need you debug the code if they&#8217;re not up to speed yet.</p>
<p>Managing, or rather, choosing NOT to manage Stream subscriptions can get you into trouble memory wise. Most Promises you see on the web don&#8217;t really show how to clean them up. Most Stream examples are the same way. Just be sure you realize their writing pseudo code to get the point across and assume you will do your due diligence by disposing of your subscriptions.</p>
<p>Lastly is the merge/pipe mania. Many will use Stream features simply because they a Stream features. New, fresh, shiny, hot. Once they get bored, they&#8217;re just another way of doing events or async Promises. Be wary of people who want to merge/pipe all the things. If they go all Katamari Damacy with Streams attempting to eat and consume MVC, you know they&#8217;ve jumped the shark. That said, I encourage you to do this in your spare time off of project/client work. The various libraries approach things differently so it&#8217;s neat to learn those differences.</p>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-5-of-7-promise-and-deferred.html" class="btn btn-primary">&lt;&lt; Part 5 &#8211; Promise Deferred</a> | <a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-7-of-7-conclusions.html" class="btn btn-primary">Part 7 &#8211; Conclusions &gt;&gt;</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Message Systems in Programming: Part 5 of 7 &#8211; Promise and Deferred</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-5-of-7-promise-and-deferred.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 15:58:10 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4729</guid>

					<description><![CDATA[Promise and Deferred (or Futures and Completers) We&#8217;ve glossed over asynchronous coding up to this point. Many from languages which have reasonable event API&#8217;s (ActionScript) to extremely nice ones (C#), it may not at first look like a problem, or even appear to be an edge case. Coming from ActionScript, it took me years to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="promises"></a></p>
<h2>Promise and Deferred (or Futures and Completers)</h2>
<p>We&#8217;ve glossed over asynchronous coding up to this point. Many from languages which have reasonable event API&#8217;s (ActionScript) to extremely nice ones (C#), it may not at first look like a problem, or even appear to be an edge case. Coming from ActionScript, it took me years to get comfortable, and understand why, Promises were helpful. Also, many in those languages either create, or have facilities that help create, orchestration code to help mitigate common asynchronous coding issues.</p>
<p><span id="more-4729"></span>But first, why asynchronous code?Â Synchronous code in GUI&#8217;s is challenging for 2 reasons.</p>
<p>The first is most UI runtimes have the code execution and drawing in the same thread. The <a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/">Elastic Racetrack</a> metaphor is often used to explain how this works. This means we have an our code doing calculations and handling user events (like clicks) done at the same time as the code that draws and redraws things to the screen. At first this seems reasonable given how fast computers are. However, as code complexity grows inline with sophisticated UI such as dynamic graphs, hardware accelerated animation, and complicated redrawing of multiple DOM elements for text and graphics in the browser&#8230; It&#8217;s a lot to do in a few milliseconds so the user doesn&#8217;t notice. That, and this all assumes the code has no orchestration to optimize this redraw part of the track, and the data processing part of the track such as <a href="http://jessewarden.com/2008/03/how-to-fix-the-flash-cs3-components.html">invalidation strategies</a>, also known as deferred rendering.</p>
<p>Second is network or I/O (input output) calls. For example, I want to show some text on this page; I know you&#8217;re German speaking based on the browser string, so I make a network request to my CMS (content management system) to get the German content. This may take a second or many seconds. In the synchronous or &#8220;blocking&#8221; world, the code would stop executing at that point and wait for that request to the server to spit back the text we need. The user&#8217;s mouse would work, but no clicks, drags, touches, double-clicks, rollovers, touch indicators, keyboard usage would function, nor would the user be able to see the UI visually update; the app looks like it&#8217;s broken. Even if it had a loading icon, it&#8217;d be paused. The UI is &#8220;locked&#8221; or &#8220;blocked&#8221;.</p>
<p>Cool, so things that require us to go outside of JavaScript for data like the server or the local disk/database, we&#8217;ll just make those asynchronous, which the Browser developers have done for us. The same holds true for server development platforms like Node and gaming ones like Corona and <a href="http://unity3d.com/">Unity</a>. Other blocking languages like <a href="https://golang.org/">Google&#8217;s Go</a> don&#8217;t have this issue/feature.</p>
<p>This, however, creates 2 new problems specifically how to write code that &#8220;waits&#8221; for things and how to chain these scenarios without making the code unreadable or hard to follow.</p>
<p>Callbacks are the first way. We&#8217;ve seen for simple code, they are the fastest, easiest, and most flexible way to do that. &#8220;Whenever you&#8217;re done, homey, call me&#8221;. Below is how JQuery does asynchronous loading of data from t3h interwebz:</p>
<pre lang="javascript">$.ajax({
  url: "http://jessewarden.com",
  success: function(data)
  {
  	console.log("loaded data:", data);
  }
});</pre>
<p>&#8220;Load data from here, and call this function when it worked, passing me the data as the 1st parameter, kthxbai.&#8221;</p>
<p>Events were another attempt to do that for multiple people who wish to know about some async event. You can utilize the same API, and your code looks the same, and the key here is that it works the exact same whether synchronous or asynchronous. The pseudo code below shows synchronous click code with asynchronous image loading code. Notice how the API looks and works the same, yet the firstÂ callback function fires immediately when you click in the same call stack, whereas the 2nd fires after some random amount of time, never in the same execution stack.</p>
<pre lang="javascript">function onClick(event)
{
   console.log("clicked");
}
button.addEventListener("click", onClick);

function onImageLoaded(event)
{
   console.log("image loaded");
}
image.addEventListener("onload", onImageLoaded);</pre>
<p>That&#8217;s all well and good until you start utilize class composition; meaning you utilize many objects that have events or callbacks in a parent class. One convention is to register all the event listeners up top, and then define the event handlers below, in the order they were added. If the event handlers utilize functions, well, you just either put them nearby and make finding the functions in order no longer work, or put them below the callbacks and force those reading/debugging to jump around your class.</p>
<p>For the sake of the reader, I&#8217;ll keep the below brief, but tripling the lines of code below it is something I commonly see:</p>
<pre lang="javascript">define(["jquery",
		"Underscore",
		"com.company.project.views.InventoryView",
		"com.company.project.views.ScheduleView",
		"com.company.project.views.ProfilePopUp",
		"com.company.project.events.EventBus",
		"com.company.project.utils.InventoryUtils"], 
		function($,
					_,
					InventoryView, 
					ScheduleView, 
					ProfilePopUp,
					EventBus,
					InventoryUtils)
{
	var SomeClass = function()
	{
		init: function()
		{
			// TODO: use _.bindAll
			_.bind(this.onClick, this);
			_.bind(this.onInventory, this);
			_.bind(this.onScheduleTask, this);
			_.bind(this.onToggleProfile, this);
			_.bind(this.onToggleEditProfile, this);

			$("#SubmitButton").click(this.onClick);
			$("#InventoryButton").click(this.onInventory);
			$("#ScheduleTask").click(this.onScheduleTask);
			$("#ToggleProfile").click(this.onToggleProfile);
			$("#ModalProfileEditForm").click(this.onToggleEditProfile);
		},

		onClick: function()
		{

		},

		onInventory: function()
		{

		},

		onScheduleTask: function()
		{

		},

		onToggleProfile: function()
		{


		},

		onToggleEditProfile: function()
		{

		},

		someHelperMethodReferencedRandomlyAbove: function()
		{

		}
	};
	return SomeClass;

});</pre>
<p>It looks nice at first, but then becomes a long class you have to constantly scroll up and down through. It gets worse as those event handlers and methods either grow in size, number, or have comments attached to them. You&#8217;ll notice the above is using UI events; this can be deceiving if some of those callbacks are actually listening to global pub sub messages. It gets confusion which functions are responding to global events and which are responding to local UI ones. Your unit tests also start to get pretty long as well. Languages which handle scope like <a href="http://coffeescript.org/">CoffeeScript</a> and <a href="http://www.typescriptlang.org/">TypeScript</a> can help a little, but you still end up with the same problem: lot&#8217;s of code that&#8217;s hard to pin down to localized functionality; i.e. &#8220;all the stuff this class does about this one thing is right here&#8221; vs. spread out all over the place.</p>
<p>Now, remember, there are those of us from other languages/platforms where this was the norm and considered ok (even if you didn&#8217;t have a deadline). Worse, anonymous functions in some languages needed to be scoped to SOMETHING else the garbage collector would eat them leading to less terse code capabilities without a language change (i.e. Lambdaâ€<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2122.png" alt="™" class="wp-smiley" style="height: 1em; max-height: 1em;" />s in t3h newer Java). JavaScript and Lua&#8217;s friendless to lamda/anonymous functions in terms of the Garbage Collector not eating them in Mark and Sweep phases means they are a common way to reduce code length in larger code bases at a tiny cost to function creation time (anonymous functions vs. class member / Object.prototype ones).</p>
<p>Where async code really starts to break down is with data orchestration and animation: 2 common asynchronous operations central in UI development. Additionally, we have no idea if any of those events already happened before the class executed. The UI events that are user gestures (the user clicked on something), we don&#8217;t care, but the model or other UI asset changes, we do. This is why you&#8217;ll often see those event handlers called at the bottom of the init to &#8220;set the class up in case she&#8217;s late to the data party&#8221;.</p>
<p>Jake Archibald has a great, and often used example, that wonderfully illustrates how the above provides a false sense of security, specifically around loading of an image. I&#8217;ll copy that example here verbatim:</p>
<pre lang="javascript">var img1 = document.querySelector('.img-1');

function loaded() {
  // woo yey image loaded
}

if (img1.complete) {
  loaded();
}
else {
  img1.addEventListener('load', loaded);
}

img1.addEventListener('error', function() {
  // argh everything's broken
});</pre>
<p>2 important points in this example.</p>
<p>First, we burden the consumer, the developer using the class that emits events, to check if it already fired, and if so, manually fire her event assuming the event handler accepts a function call without an event parameter; JavaScript does, CoffeeScript(?), TypeScript, and Dart you have to specifically mark those functions to have the events as optional parameters.</p>
<p>Second, my SomeClass example above doesn&#8217;t have any error handling at all. In most apps, at best, they log errors with little to no user experience thought given around those scenarios. That said, very rarely do any of them react to errors that happened before their instantiated for the user (ie a graph is shown, but the data that was supposed to be loaded before it was shown failed to load). No one wants to spend time creating user experiences around a broken server, but it&#8217;s important. Pitching clients to spend a lot of their application development budget on designing user experiences around things breaking seems counterintuitive to quality software craftsmanship. Thus, this is often left to developers who have little time for such concerns, hence why error handling is often such a horrible experience in many applications. It&#8217;s not their responsibility, its the Designer(s). Catch 22, sucka!</p>
<p>When you take into account both events already happening before you&#8217;ve arrived on the scene as well as errors, you can see how the code above gets much more verbose, and complicated to follow.</p>
<p>One common work around at least in MVC applications, is to allow View classes to be extremely friendly to null values in the Models. That way, if the data isn&#8217;t loaded let, they can show either a loading or something to the user while it loads or fails, otherwise they can immediately draw the model when they&#8217;re shown. The thinking goes &#8220;someone else will handle orchestrating everything in the correct order later&#8221; and even &#8220;somehow allow this to be easily refactored&#8221;. This can work if your Models aren&#8217;t that complicated, but still makes the code quite verbose.</p>
<p>The second place the SomeClass example starts to break down is when you have multiple asynchronous events that depend on each other.</p>
<pre lang="javascript">var userView = {
	userModel: null,
	imageTag: null,
	showAvatar: function()
	{
		var imageURL = userModel.avatarURL;
		imageLoader.get(imageURL, function(bitmapData)
		{
			imageTag.showBitmapData(bitmapData);
		});
	}
};</pre>
<p>You&#8217;ll notice in the above simple JavaScript View, if both the model data for the user is not yet loaded from the server AND the HTML and CSS needed to display the image which also needs to be loaded, the View won&#8217;t work. 2 options here: either check for null and do nothing assuming &#8220;you didn&#8217;t load the data for me idiot, I&#8217;m not showing anything, but will be nice to you and not throw errors&#8221; or put the burden on the developer using the View to get both of those things ready ahead of time.</p>
<p>Many MVC and web application tutorials out there assume you have good REST services that give you only the data you need, and you only need to make 1 call for the entire app or per section the user see&#8217;s with a good set of data caching code behind it. Backbone is notoriously seductive in this respect regarding who it&#8217;s Models are built around this with no guidance given to those who aren&#8217;t actually hitting REST services.</p>
<p>If you&#8217;re a JavaScript client developer, and you have a bad ass Node developer who has your back and y&#8217;all can communicate often as requirements changeâ€¦ you have it quite well, my friend.</p>
<p>This is simply not how enterprise applications work in the real world, although I&#8217;m seeing this change once .NET/Java business tier developers realize their jobs aren&#8217;t in jeopardy because of Node. You&#8217;re often building atop of .NET or Java backends that are several years old, many of which were in support of page based web sites or desktop applications long before you got involved. Getting the back-end team to refactor this for the best user experience takes an act of God, especially if you&#8217;re one of hundreds of applications that consume their services.</p>
<p>Unless you got Node into the mix, you&#8217;ll be making many calls, often multiple times, before a particular View/Screen can be shown to the userâ€¦ in addition to your other data orchestration duties. Sometimes you&#8217;re lucky if you abstract these multiple calls away into a single class that dispatches 1 event. If you&#8217;re not, you usually have the two common problems: multiple classes that only have pieces of the data you need that continually needs refreshing or lots of data on the client you have to parse, such as the case in dashboards and graphing applications. This isn&#8217;t just ajax calls we&#8217;re talking about either; this could be JavaScript code running on the client that that needs to run long running parsing code that may or may not include an ajax call, image and other media assets, and various multiple authentication calls from a variety of servers.</p>
<p>For example, many financial applications often pull data from a variety of back-end data sources to show on 1 screen. Whether these are different sub-domains, or a single REST/SOAP/RPC server, they could still all work slightly differently and take varying amount of times to respond. Sometimes you have to call them in a certain order since each successive call gives you a token/id/session cookie needed for the following call for the actual data, some of which you can&#8217;t cache because the nonce tokens (prove you&#8217;re a user who&#8217;s logged in) can expire quickly for financial data.</p>
<p>Let&#8217;s show an example where you first need to get some user info that needs to be obtained to snag the user&#8217;s current token (which changes often) so you can then get info on a particular financial transaction (something the user bought) which is then used to charting data related to it&#8217;s id + type (which the server has conveniently stashed a bunch of huge JSON files on a <a href="https://www.heroku.com/">Heroku</a> friendly CDN somewhere so you can parse on the client to show charts). </p>
<p>However, that last call has a TON of data, so you&#8217;re using a polyfill (a library that allows you to use future HTML5 functionality, today) that supports WebWorkers (threads in JavaScript) so you can parse the data safely and attempt save to LocalStorage to avoid the slow latter part of the process again if the user views a particular transaction again later. I&#8217;ve also had cases where the type dictates which type of data we have, thus requiring another parsing call and a basic fork in the path of how you parse the code. I&#8217;ve also left out the fun parts of debugging unknowingly neutered ArrayBuffers&#8230; but lets keep it simple (lulz).</p>
<p>Quite a mouthful yet common in the screwed up world of Enterprise Software.</p>
<pre lang="javascript">var currentClientToken = null;
var clientID = null;
var transactionID = null;
var graphWorker = null;
var done = false;

function getCompleted()
{
	return this.done;
}

function getClientToken(clientID, transactionID)
{
	this.done = false;
	this.clientID = clientID;
	this.transactionID = transactionID;
   $.get("/getClientInfo", clientID, this.onGetClientTokenSuccess, this.onGetClientTokenError);
}

function triggerGenericError(error)
{
	EventBus.trigger("GetChartingInfo:error", error);
}

function onGetClientTokenError(error)
{
	this.done = true;
	this.triggerGenericError(error);
}

function onGetClientTokenSuccess(data)
{
	try
	{
		var clientVO = ClientFactory.get(data);
		this.currentClientToken = clientVO.token;
		$.get("/getTransactionInfo", 
			{token: this.currentClientToken, transactionID: this.transactionID}, 
			this.onGetTransactionInfoSuccess, this.onGetTransactionInfoError);
	}
	catch(err)
	{
		this.triggerGenericError(err);
	}
}

function onGetTransactionInfoError(error)
{
	this.triggerGenericError(error);
}

function onGetTransactionInfoSuccess(info)
{
	try
	{
		var transactionVO = TransactionFactory.get(info);
		var currentTransactionURL = "https://sub.company.com/project/graphingcdn/" + transactionVO.id + "/?clientID=" + this.currentClientToken;
		$.get(currentTransactionURL, this.onGraphDataSuccess, this.onGraphDataError);
	}
	catch(err)
	{
		this.triggerGenericError(err);
	}
}

function onGraphDataError(error)
{
	this.triggerGenericError(error);
}

function getGraphWorker()
{
	if(this.graphWorker == null)
	{
		this.graphWorker = new Worker("GraphFactory.js");
		this.graphWorker.onmessage = function(event)
		{
			this.onGraphDataParsed(event.data);
		};
	}
	return this.graphWorker;
}

function onGraphDataSuccess(graphData)
{
	getGraphWorker().postMessage(graphData);
}

function onGraphDataParsed(graphVO)
{
	if(graphVO != null)
	{
		this.done = true;
		EventBus.trigger("GetChartingInfo:success", graphVO);
	}
	else
	{
		// parsing failed
		EventBus.trigger("GetChartingInfo:error", error);
	}
}</pre>
<p>&#8230; to recap our problems, we now have:</p>
<ol>
<li>lots of code</li>
<li>you have to scroll to find where an event is handled</li>
<li>finding event handlers for events registered within event handlers makes it even harder to follow</li>
<li>using if statements to handle potential race conditions</li>
<li>burden to ensure sequence can only start once with ability to stop it at any point</li>
<li>forced to remove event listeners to help garbage collection</li>
<li>code not fully shielded from uncaught exceptions</li>
<li>burden of error handling can make API unwieldy</li>
</ol>
<p>WAT DO!?</p>
<p>Science has shown that less code equals better software. Through 1 study at least.</p>
<p>Enter the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Promise</a> (known as <a href="https://www.dartlang.org/docs/tutorials/futures/">Futures</a> in Dart). They are a way to make asynchronous code look and feel like synchronous code.</p>
<p>Our &#8220;use&#8221; of the above is turned into 8 lines of code (6 if you cuddle, but Machete don&#8217;t cuddle):</p>
<pre lang="javascript">getGraphData().then(function()
{
	EventBus.trigger("GetChartingInfo:success", graphVO);
},
function(error)
{
	EventBus.trigger("GetChartingInfo:error", error);
});</pre>
<p>Now, using Underscore and some refactoring using your module system of choice, you could refactor the above to be similar without Promises:</p>
<pre lang="javascript">EventBus.on("GetChartingInfo:success", function(graphVO)
{
	drawIt(graphVO);
});
EventBus.on("GetChartingInfo:error", function(error))
{
	console.error("GetChartingInfo:error:", error);
});
getGraphData();</pre>
<p>9 (7c) lines vs. 8 (6c); not bad. However, not apples to apples either. They do completely different things and the Event way doesn&#8217;t guarantee the same order in the same stack like Promises do. Subtle, but painful for n00bs to debug when they don&#8217;t know what&#8217;s going on. Heck, it&#8217;s painful for me!</p>
<p>The promise way only has 1 callback. The Events have multiple potential ones.</p>
<p>The events must be registered as listeners first before the call to getGraphData happens. If the events are not registered before getGraphData is called, you do not get the data. While getGraphData may internally cache the data, you must call it again after your listeners are registered to get this data. For smaller applications, this is easy; for larger ones, this is more challenging. It also puts a burden on those types of classes to make a caching decision sooner to make an easier API to consume.</p>
<p>The Promise does not care if you call it before the value(s) internally have been fetched from the server yet or not; you can call it anytime and get the same result. There is never a race condition problem using Promises as opposed to Events.</p>
<p>Also, by default, most Promises assume you&#8217;re caching in RAM by default based on the last return value if you follow the Promise/A spec.</p>
<p>API wise, it should be noted that the Event by default allows multiple responders to hear about a success or failure, whereas the Promise is only executed with 1 callback. This is neither good nor bad, just something be aware of when comparing the callback nature of Promises compared to Events.</p>
<p>A minor point, but the events now have a message chosen. You now need a way to track that message. If you just use a magic string, fine, but for large applications you tend to use some form of enumeration or constant class to help both management, strong-typing &#038; code hinting for IDE&#8217;s that support it, and to ease the developer&#8217;s need to View all possible messages in a central place without a grep. Now a decision must be made; where do these enumerations go? In the class dispatching as statics/constants? Is it 1 class that supplies all global pub sub events for the entire application? Each has their pro&#8217;s and con&#8217;s, but both include more code, cognitive overhead, and crap for you to deal with.</p>
<p>Lastly, most Promises &#038; promise libraries will execute on the next tick whereas most event, pub sub, and streaming libraries do not. Yes, you can add a setTimeout(func, 0), but that&#8217;s a hack on top of an API most assume works, and codes their API as, synchronously. There are a variety of use cases that aren&#8217;t described very well so I&#8217;ll cover that below regarding expecting order of execution to work, whether in synch or async code. This is why many pub sub libraries have extra error handling on removing listeners because if it&#8217;s in the middle of a dispatch, you can accidentally <a href="https://web.archive.org/web/20030203013431/http://chattyfig.figleaf.com/flashcoders-wiki/index.php?betabugs">prevent others from getting the message</a>.</p>
<p>Now, Jake&#8217;s article covers all you need to know about how Promises work, and Q&#8217;s documentation is pretty legit as well to help you create Promises as well as work with libraries that aren&#8217;t Promises out of the box.</p>
<p><A name="doneyet"></a></p>
<h3>Done Yet?</h3>
<p>Promises, whether ES6 or Q, store the state of whether the Promise is done or not internally. You don&#8217;t have write code to do that; it&#8217;s part of them implementing the state machine part of the Promises/A spec. The Event option, however, has to allow the &#8220;done&#8221; boolean to be managed amongst the many callbacks.</p>
<p>This internal state management has a positive effect on sub-sequent calls with the same data, specifically getClientToken, getTransactionInfo, loading of the transaction JSON data, and receiving the parsed data from the WebWorker. For Promises, they&#8217;ll simple cache the data and re-deliver it usually immediately in the next tick (next time the stack is unwound then wound).</p>
<p>In the Event abstraction, you&#8217;ll have to do that yourself. In both cases, you&#8217;ll have to utilize whatever local storage option you wish to use (cookies, local storage, app cache, etc), but this functionality of locked data is built into Promises; you don&#8217;t have to code it, it&#8217;s built in + expected behavior. This includes multiple calls that could utilize multiple Promises internally. In our case, that&#8217;s about 4 Promises that each has the built-in ability to store data if it hasn&#8217;t changed.</p>
<p>You can also refactor asynchronous code that is not a Promise to be a Promise. That is one way developers have attempted to solve the above problems.</p>
<p><A name="solvinglotsofcode"></a></p>
<h3>Solving Lots of Code</h3>
<p>Promises are made part of async API&#8217;s. As such, instead of first registering for an event before calling something that will trigger it, you instead just call the method and the Promise is the returned value. That&#8217;s 2 lines of code to 1. Like callbacks.</p>
<p>This has larger ramifications, though, down the line when you&#8217;re async call is part of a series of async call allowing them to be chained as well as put into groups where they all must complete before another operation can succeed. This further cuts down on needing to define event handlers.</p>
<p><A name="scrolltofindcode"></a></p>
<h3>Scroll to Find Code</h3>
<p>No more scrolling, it&#8217;s defined inline. The call and the responses are all next to each other.</p>
<p><A name="nestedeventhandlerregistration"></a></p>
<h3>Nested Event Handler Registration</h3>
<p>This problem isn&#8217;t solved immediately with Promises. You can get into situations where people do not return Promises from async code, and they end up doing work in the success handlers. Through refactoring you can flatten these deeply nested chains. <a href="https://plus.google.com/+ThomasBurleson/posts">Thomas Burleson</a> has <a href="https://github.com/ThomasBurleson/angularjs-FlightDashboard">a great example</a> where he shows both.</p>
<p><A name="handlingraceconditions"></a></p>
<h3>Handling Race Conditions</h3>
<p>Part of the spec for Promises is to solve this issue. Promises will automatically call their success or error method if the event has already occurred. This, again, reduces the amount of code you need to write when consuming async services. Additionally, it adds flexibility to call them in any order, at any time you need to; no need for orchestration/setup code to ensure everything is &#8220;ready for the data events that will fire and YOU NEED TO BE THERE FOR&#8221;. You instead react. This is part of where the &#8220;reactive&#8221; part comes in Functional Reactive Programming.</p>
<p>Finally, Promises have an internal state machine convention that they only ever complete once; so you don&#8217;t have to worry about your error or success methods firing more than once. They are not like events in this aspect which are known to fire many times.</p>
<p>This is one of the main problems that Events and Pub Sub run into when the application starts to grow in size and developers. </p>
<p><A name="abortingsequence"></a></p>
<h3>Aborting Sequence</h3>
<p>Promises do not solve the abort sequence; i.e. you cannot easily start a long async Promise or chain of Promises once they&#8217;ve started. De-reffing the parent in hopes the child will get garbage collected isn&#8217;t sure fire, and adding API&#8217;s to a Promise based class is a more prudent option, although, more work in the case of many Promises through Composition.</p>
<p>More advanced Promise API&#8217;s such as Dart&#8217;s <a href="https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-async.StreamController">StreamController</a> and RX.js&#8217; <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/libraries/rx.backpressure.md">Backpressure</a> have the API&#8217;s you need to wrap Promises with the ability to stop async sequences, or even pause the events being emitted from the emitter. However, both incur a completely different paradigm of programming so it&#8217;s not as simple as &#8220;oh, I&#8217;ll just use this awesome library/x-compiler&#8230;&#8221;. We&#8217;ll get into that in the Streams section.</p>
<p><A name="nomorecleanupcode"></a></p>
<h3>No More Cleanup Code</h3>
<p>Promises, if they&#8217;re values are non-global and the chains are local to the function block, will get eaten by garbage collection if you de-reference them.</p>
<p>From a memory standpoint, this can be a blessing or a curse. Promises are ensured to only execute one time, and cache the value each additional call assuming the inputs don&#8217;t change, all while retaining the same code execution order. However, they basically act like a getter; they cache the data they are referencing as a form of <a href="http://stackoverflow.com/questions/10314056/usage-of-observable-pattern-in-javascript">Observers</a>, albeit with 1 listener to start. Note, the Observer pattern is different than what stream API&#8217;s refer to regarding <a href="http://reactive-extensions.github.io/RxJS/">Observables</a>. People will use the word &#8220;observable&#8221; to either refer to something that emits change events like the Observer design pattern, or a watchable property/stream in something like RX.js/<a href="http://baconjs.github.io/">Bacon.js</a>. For large data sets, images, etc. you may not wish to leave this stuff laying around in RAM.</p>
<p>Check out this post (plus the comments full of lulz) from <a href="http://sealedabstract.com/code/broken-promises/">Drew Crawford</a> talking about how brazenly just caching all data in Promises isn&#8217;t always a good idea.</p>
<p><A name="shieldedfromexceptions"></a></p>
<h3>Shielded From Exceptions</h3>
<p>In the native implementations, Promises are built around the concept of success and failure. This includes built-in support for if an exception is thrown in a constructor it calls the error callback. Additionally, you can interpret successful responses from the server as a mistake and cause an error condition safely.</p>
<p>That said, the burden of good error handling is still on the developer in case an error does bubble up through a deep Promise chain, you want a good idea of where it came from. The same goes for good synchronous error handling through tried and true try/catch blocks within more complex Promise operations. Looking through the stack trace to work your way back down is still required in some cases which, again, can be mitigated with an effective logging solution. Theoretically <a href="http://swannodette.github.io/2013/08/31/asynchronous-error-handling/">yield</a> used within a <a href="http://wiki.ecmascript.org/doku.php?id=harmony:generators">Generator</a> function could help mitigate some of the error hunting as well.</p>
<p>Also, take note some Promise libraries take the positive initiative to allow you to get stack traces that areâ€¦ you knowâ€¦ actually useful in debugging such as Q (check out <a href="https://github.com/kriskowal/q">longStackSupport = true</a>) and Bluebird&#8217;s <a href="https://github.com/petkaantonov/bluebird/blob/master/API.md#promiselongstacktraces---void">longStackTraces</a>. these types of debugging features are NOT in Angular&#8217;s version of <a href="https://docs.angularjs.org/api/ng/service/$q">$q</a>, and it&#8217;s Promise API. Do the hard work of being proactive yourself with good try/catch error messages and logging.</p>
<p>Also note, many Promise libraries will allow you to apply multiple catches to differentiate between the various types of async errors which is a wonderful practice you should endeavor to do.</p>
<p><A name="nexttick"></a></p>
<h3>Next Tick</h3>
<p>Some Promise libraries will make a big deal about &#8220;nextTick&#8221;. The reason is most people when writing synchronous code expect the same order of execution no matter how many times the code is run. While Promises aren&#8217;t technically synchronous code, you write it as such. </p>
<p>For example, we all expect the function below to print out 1, 2, 3 no matter how many times it&#8217;s called:</p>
<pre lang="javascript">function dreamMachine()
{
	console.log("1");
	console.log("2");
	console.log("3");
}</pre>
<p>We also expect the function below to print out 1, 3, 2 no matter how many times it&#8217;s called:</p>
<pre lang="javascript">function dreamMachine()
{
	console.log("1");
	Q.fcall(somePromise).then(function()
	{
		console.log("2");
	});
	console.log("3");
}</pre>
<p>This is one feature Promises have above simple Pub Sub because your callbacks are fired in the same order regardless of how long the response takes, and if the data is cached or not.</p>
<p>Those who get mad about it are the ones who want faster code, typically server-side Node developers. The nextTick is often at a minimum a setTimeout(runTheThenFunction(), 0). This&#8217;ll significantly warp benchmarks that make the code look slow whereas in reality the code isn&#8217;t actually using CPU.</p>
<p>However, it IS a problem in that the code still takes more time and can significantly increase unit test suite test runner time. There are various Promise/A+ spec compliant libraries that will give you a flag to turn this off. This is for developers who know exactly why you&#8217;ll get 1, 2, 3 in some situations above. If you don&#8217;t know why that can happen, leave the setting off, heh!</p>
<p>Be aware, Node.js has <a href="http://nodejs.org/api/process.html#process_process_nexttick_callback">a more efficient nextTick</a> with configuration options.</p>
<p>Another use case is asynchronous initialization. Some objects/classes have significant amounts of asynchronous setup they have to do. You want an opportunity to be aware of some of these operations, say the loading of images in gaming Sprites, or using a server-side logging that has JSON file based configuration values is must load and parse before being used. Incidentally, this makes writing invalidation routines on top of existing GUI code a big easier.</p>
<p>Finally, in the case of networking operations, you don&#8217;t always want to impose knowledge of order of operations on the user. Instead, let them set and call things in any order, and let the class figure out the true order on the nextTick/frame.</p>
<p>For example, imagine if JQuery&#8217;s ajax didn&#8217;t have object initialization as it&#8217;s API. Instead of:</p>
<pre lang="javascript">$.ajax({
  url: "http://jessewarden.com",
  success: function(data)
  {
  	console.log("loaded data:", data);
  }
});</pre>
<p>It&#8217;d be:</p>
<pre lang="javascript">var operation = $.ajax();
operation.url = "http://jessewarden.com";
operation.dataType = "html";
operation.type = "GET";
operation.success = function(data)
{
	console.log("loaded data:", data);
};
operation.load();</pre>
<p>You not only have to learn an API, but the order in which the methods are called just to make a simple GET call? What if even more code later continues to modify, or even overwrite the operation&#8217;s parameters?</p>
<p>Using nextTick, calling order doesn&#8217;t matter. Internally, the actual XHR call won&#8217;t be made until the next frame anyway, so the ajax operation can handle setting everything up in the order it needs. This follows OOP encapsulation principles, and makes life easy on the developer.</p>
<p><A name="promisepros"></a><H3>Promise Pros</h3>
<p>Promises significantly reduce the amount of code you have to write for asynchronous operations where you&#8217;d traditionally use callbacks or events.</p>
<p>They also localize it vs. spreading it out like events and callbacks are want to do. Just be sure you practice flattening some Promise chains so you don&#8217;t end up with the opposite problem of Promise chain hell vs. callback hell.</p>
<p>They also make chaining multiple asynchronous operations together much easier to read and debug.</p>
<p>They help reduce race conditions when the Promise already has a cached value, and merely calls the callback immediately. For low memory items, this also has the side benefit of caching data in memory for expedited calls later on, especially for those classes/Views initialized later in the application lifecycle. They also make writing asynchronous libraries easier on the consumers because they can call their setup calls in any order knowing the actual resolving of them will occur on the next frame.</p>
<p>Finally, you can write your code and not have to care something is synchronous or asynchronous; it looks and is written in a synchronous way.</p>
<p><A name="promisecons"></a><H3>Promise Cons</h3>
<p>For those who are new to Promises, as I mentioned, they end up creating callback hell using Promises. Rather than creating their own operations that return Promises, they instead merely use Promises and continue to nest them. Again, check out Thomas Burlesson&#8217;s <a href="https://gist.github.com/ThomasBurleson/7576083">great example</a> where he shows how you flatten deeply nested Promise chains. Once you practice, you can quickly flatten these trees as you create them. Eventually you&#8217;ll start writing methods that return Promises by default making your life easier. Like once you memorize a for loop&#8217;s syntax, you never think about it again.</p>
<p>For low memory situations on mobile, you could get in trouble when caching the data in Promises. While you&#8217;re supposed to follow the Promise/A spec and ensure Promise&#8217;s fullfilled state stays true and never changes the data, care must be taken to ensure you aren&#8217;t keeping these around unnecessarily, especially on mobile devices. This isn&#8217;t necessarely indicative of Promises, rather caching in general, which is a commonly hard programming problem. They are just brought up since most Promises handling async operations are often around data, your want to cache it.</p>
<p>Caching isn&#8217;t straightforward either. Some libraries help in this regard, but basic programming for by value vs. by reference apply. When getting values you&#8217;re basically assuming the developer doesn&#8217;t change them if they&#8217;re by ref. Cloning has performance impacts as well for deeply nested objects. Following the Promise/A spec with regards to not changing the value is often based on convention and isn&#8217;t always easily enforced. Don&#8217;t get me started on the insanity of sharing <a href="v">ArrayBuffers</a> across <a href="http://www.html5rocks.com/en/tutorials/workers/basics/">WebWorkers</a>; shiz is magic death.</p>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-4-of-7-publish-subscribe.html" class="btn btn-primary">&lt;&lt; Part 4 &#8211; Publish Subscribe</a> | <a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-6-of-7-streams.html" class="btn btn-primary">Part 6 &#8211; Streams &gt;&gt;</a></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
