background preloader

JavaScript Promises: There and back again

Ladies and gentlemen, prepare yourself for a pivotal moment in the history of web development… [Drumroll begins] Promises have arrived natively in JavaScript! [Fireworks explode, glittery paper rains from above, the crowd goes wild] At this point you fall into one of these categories: People are cheering around you, but you're not sure what all the fuss is about. What's all the fuss about? JavaScript is single threaded, meaning that two bits of script cannot run at the same time, they have to run one after another. As a human being, you're multithreaded. You've probably used events and callbacks to get around this. var img1 = document.querySelector('.img-1'); img1.addEventListener('load', function() { // woo yey image loaded}); img1.addEventListener('error', function() { // argh everything's broken}); This isn't sneezy at all. This doesn't catch images that error'd before we got a chance to listen for them, unfortunately the DOM doesn't give us a way to do that. Promise terminology fulfilled Related:  ES6/ES20152JS

Using JavaScript Promises to Reason About User Interaction In functional programming, we rarely worry about concurrency primitives like threads. Instead, we use abstractions to make our code easier to reason about. In JavaScript, a Promise is the most common abstraction we encounter. It is usually associated with an Ajax request. We often use abstractions to reason about our concurrent code, but those abstractions can apply in other situations, as well. Let's take a look at an example. In order to determine if a user already owns the content, we need them to be signed in. Any time we're dealing with user interaction, it is inherently asynchronous. A user may or may not be signed in. class UserSession constructor: (@Q, @AuthModals, @Session) -> @_session = @Session.get() signIn: -> @_authDeferred = @Q.defer() @_resolveOrPrompt() @_authDeferred.promise completeSignIn: (data) -> _resolveOrPrompt: -> if @_session?. There's a lot going on here. This is incredibly powerful. We apply the same pattern here.

ECMAScript 6: New Features: Overview and Comparison Futures and promises In computer science, future, promise, and delay refer to constructs used for synchronizing in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete. The terms future, promise, and delay are often used interchangeably, although some differences in usage between future and promise are treated below. Specifically, when usage is distinguished, a future is a read-only placeholder view of a variable, while a promise is a writable, single assignment container which sets the value of the future.[4] Notably, a future may be defined without specifying which specific promise will set its value, and different possible promises may set the value of a given future, though this can be done only once for a given future. Implicit vs explicit[edit] Promise pipelining[edit] Consider an expression involving conventional remote procedure calls, such as: t3 := ( x.a() ).c( y.b() )

Techniques With ES6 Default Parameter Values, Spread, and Rest Default Behavior Default parameter values let function parameters be initialized with default values when no value or undefined is passed. We can also specify a function as a default value. Required Parameters Another technique with default parameter values is to allow a function to declare required parameters. Copy Arrays and Modify Them In ES5, we can use Array#concat or Array#slice to make a copy of an array. In ES6, copying an array is even easier with the spread operator. Copy Objects and Modify Them In ES5, we can borrow a utility function such as jQuery#extend, _.assign to make a copy of an object: In ES6, we can use the built-in function Object.assign: Another way is to use the spread (…) operator: Note: spread operator for objects isn't supported in ES6. Avoid Function.prototype.apply Some functions such as Math.max, Math.min, Date, etc. require a list of parameters. What if we have a list of parameter values contained in an array? Forget Arguments arguments is not an array. All in One

Generators in Node.js: Common Misconceptions and Three Good Use Cases Generators have been all the rage lately. Many Node developers (including myself!) are excited and intrigued about writing their asynchronous code like this: However, this is just one use case (although a clever one) of using generators. In this article, we will explore the strengths of using generators. There is a GitHub repository with the code samples we will go through that you can check out. What is a generator? Generators are function executions that can be suspended and resumed at a later point; a lightweight coroutine. A generator starts in a suspended state. Generators also have a built-in communication channel with yield: The yield keyword must always yield some value (even if its null). In addition to communicating values, you can also throw exceptions into generators with gen.throw(new Error(‘oh no’)). Generators may be used for iteration via the shiny new for of loop: What is yield* all about? A common misconception Now, we write a similar function using generators: Summary

Promise & Deferred Objects in JavaScript Pt.2: in Practice • Chris Webb In part 1 of this post, I spent a lot of time looking at the theory of promises and deferreds: what promises are and how they behave. Now it’s time to actually explore some ways to use promises and deferreds in JavaScript and dive into some best practices. I’ll start with some basic uses and examples of promises and then will dive into a number of specifics pertaining to using promises in jQuery. While the exact specifics of the API may vary from your chosen library, there is enough overlap in concepts to illustrate the use of promises. Note: The code samples will use jQuery in spite of jQuery’s deviations from the Promise/A proposal, which is particularly noticeable in the case of error handling and when working with other promise libraries. Since part 1 discussed and included links to in-depth articles on the topic, I will refrain from saying anything else about it in this post. These patterns can be combined or used separately building up complex tasks and workflows. Ajax Timing Notes

Deploying ECMAScript 6 This blog post describes the options you have for deploying ECMAScript 6 in current JavaScript environments. It is selective w.r.t. the amount of tools it covers. If you want a comprehensive list of tools, I suggest you look at Addy Osmani’s “ECMAScript 6 Tools”. Consult the blog post “Using ECMAScript 6 today” for an overview of ES6 features. Using ECMAScript 6 today What options do you have for using ECMAScript 6 today? ECMAScript 6 features are continually appearing in engines. Especially if you take support for legacy engines into consideration, compiling ES6 to ES5 will be the only viable option for using ES6 for quite a while. The nice thing about ES6 is that it is a superset of ES5, which means that all of your ES5 code bases are already valid ES6. Using ECMAScript 6 natively As soon as the first engine fully supports ES6 and until all non-ES6 engines go away, a hybrid approach could be used for client-side apps: Transpilation tools Choosing a transpiler Static transpilation ES6 REPLs

Researchers Wirelessly Power 40 Phones From 5 Meters Away Researchers from KAIST in Daejeon, South Korea have managed to extend the reach of wireless power transfer technology, bringing us closer to a world where phone and tablet chargers are as obsolete as MC Hammer’s parachute pants. The new technology, called “Dipole Coil Resonant System (DCRS),” can charge up to 40 smartphones simultaneously from 5 meters away. The DCRS transfers electric power wirelessly through the use of transmitters and a specially designed coil structure. The Dipole Coil Resonant System (DCRS) can charge up to 40 smartphones simultaneously from 5 meters away. The new method improves on a 2007 experiment conducted by researchers from MIT. That concept, called WiTricity (as in wireless electricity), was used to wirelessly power a 60-watt light bulb from over 2 meters away. In a press release, Prof. In its current state, the DCRS is said to have the capability to power a large LED TV and three 40-watt fans from 5 meters away.

Getting up to speed with Gulp - @eliostruyf This is the next article of my getting up to speed series. This article is completely devoted to Gulp. In the previous article I explained Node.js and NPM, but I also mentioned Gulp a couple of time. As you get in this world of JavaScript focussed development, you will see that Gulp (or Grunt – depending on the developers' preference) often used for various kind of things. Gulp logo So what is Gulp exactly? Gulp: Automate and enhance your workflow As the official Gulp website states, Gulp is a tool to automate and enhance your workflow and is achieved via tasks. Transpiling TypeScript to JavaScriptStarting a web server (like you did in the previous article)Building a production package of your design filesRunning a watch on files to do something when the files have been changedUploading files to SharePoint > in the Yeoman display templates generator Gulp tasks are used to upload files, set metadata to the files, and more. The list can go on and on. Installing Gulp $ npm install -g gulp-cli