Using $q.all() to Resolve Multiple Promises

If you have a lot of promises in Angular that need to be run sequentially, you can go about it in one of two ways. There is the classic way of chaining callback functions together to achieve the desired result. Assume that all of the functions in the example below follow this format:

function promiseX() {
    let deferred = $q.defer();
    
    ajaxCall().then((response) => {
        deferred.resolve(response);
    }, (error) => {
        deferred.reject(error);
    });
    
    return deferred.promise;
}

Consider the way of callback chaining your promise results.

let values = [];
promiseAlpha().then((val1) => {
    values.push(val1);
    promiseBeta().then((val2) => {
        values.push(val2);
        promiseGamma().then((val3) => {
            values.push(val3);
            complete();
        });
    });
});

This, as you can see, is not very pretty at all, and will make it difficult to a) get the resolved value of each promise and use it and b) chain more than a few promises without pulling your hair right out of its sockets. Thankfully there is an alternative in the form of $q.all().

The $q.all() method takes either an object or an array of promises and waits for all of them to resolve() or one of them to reject() and then executes the provided callback function. The values returned from the resolve function are provided depending on the way you give the promises to all().

If you provide them as an array, then the values will be available as an array with the same corresponding order of the promises array. For example:

let promises = [promiseAlpha(), promiseBeta(), promiseGamma()];

$q.all(promises).then((values) => {
    console.log(values[0]); // value alpha
    console.log(values[1]); // value beta
    console.log(values[2]); // value gamma
    
    complete();
});

However if you provide an object literal to all, the values are attached to an object with the same corresponding property names in the all() callback. I find this way a lot easier because in most (but not all) cases you will have a set number of promises to complete.

let promises = {
    alpha: promiseAlpha(),
    beta: promiseBeta(),
    gamma: promiseGamma()
}
$q.all(promises).then((values) => {
    console.log(values.alpha); // value alpha
    console.log(values.beta); // value beta
    console.log(values.gamma); // value gamma
    
    complete();
});

This article comes out of a situation where I had to match values against ids from lists returned from an API, where the list data was not preloaded. As you can see, $q.all() becomes a very useful and much shorter way of chaining promise resolve()s than callback chaining.

Mocks, Stubs, and Injections: Unit Testing in Angular.JS

Unit testing in Angular is one of the framework’s biggest draws, and the framework’s huge focus on dependency injection makes it an ideal candidate for unit tests. This is very powerful when writing tests because any dependencies that your units or modules have can be easily mocked or injected, whether they are Angular modules or your own defined controllers, factories and directives.

I found that although this sounds good on paper, it can be quite difficult to achieve in a project whose build workflow involves about 12–15 gulp tasks, ~30 bower dependencies, and all of the modules written in ES6. Finding a way to compile the source files using Traceur and then loading them alongside the bower dependencies was a challenging endeavour, and this article aims to cover what I have found to be an ideal setup for unit testing a dependency-heavy Angular application using ES6 modules. This article will be quite lengthy, so feel free to skip ahead at any point.

(more…)

React-ions

I’ve been working with Angular a lot lately and I’ve been wrapped up in learning everything that comes with it, and it’s got me thinking whether full-fledged JavaScript frameworks are all they’re cracked up to be. Don’t get me wrong, I enjoy working with Angular and a lot of how it works and its design makes sense once you ignore the official tutorials and learn the best practices. But it feels like it has a lot of heft behind it, and sometimes the flow of data and UI interaction can get quite confusing once you have a large application.

I’d been seeing lots of mentions of React lately and it intrigued me enough to take a look. What I found were a lot of the things I’ve been thinking are not as simple as they could be in Angular, and a new way of thinking about UI interactions. And I really liked what I found. Now, I know that React is a library, the V in MVC while Angular is a full-fledged framework for building MVVM, MVC and MVW web applications. Library != Framework. So while I won’t be making many direct comparisons between the two, I may mention in this article some differences and similarities between them. Overall though, this is an article about what I like about React, and why I think you should take a look at it and try out some examples, even if you don’t intend to make a production application with it.

(more…)

ES6 Basics

I know I might be a little behind on this post, but I’ve been working exclusively on the front end at my new job and as a result I’ve been much more involved with JavaScript. We are using Angular.js and as part of our strategy of future-proofing (as much as you can for the front end) our application, we are using patterns likely to be used in Angular 2.0, which will use ES6 and Javascript Next functionality extensively. I’ve had to learn a lot of ES6 basics to effectively work with it and Angular together, and this article will go over what I think are the ES6 basics everyone should know.

(more…)

Learning Angular Q&A

While I’ve been learning Angular for the past couple of weeks, I’ve been able to get a pretty good idea of how the framework works as well as a lot of the best practices for it. While reflecting on what I had learned, I came up with several questions for myself to research to get a better understanding of more patterns and what I should use for certain things in Angular. Here are the questions I came up with and the results of my research.

(more…)

Highlighting JavaScript this Keyword in Sublime Text 2

I’ve looked for something like this before but I’ve only recently found it. Sublime Text 2 uses textmate themes which can use regular expressions and scopes to highlight certain keywords that are only relevant in certain languages. I got a new theme which I love called itg.flat and while the colors are great, it was lacking a highlight for the this keyword in JavaScript, which makes in harder to spot and locate scope issues.

I found this on a Sublime Text 2 forum post, which highlights the keyword. You just need to add this to the .tmtheme file for your theme, which will usually be located in {user}/Library/Application Support/Sublime Text 2/Packages/Theme - Name/ for Mac and %APPDATA%\Sublime Text 2\Packages\Theme - Name\ in Windows:

You can get rid of the bold/italic if you want or change the hex color code too. You may also want to check out the Sublime Text 2 Color Scheme Editor. Here you can see the result. Before:

before

After:

after

LINK: AngularJS Styleguide by @john_papa

This AngularJS styleguide, written by @john_papa, has been a fantastic resource for me while learning Angular:

https://github.com/johnpapa/angularjs-styleguide

Among the key takeaways in style that I found most important were the following:

  1. Wrap all angular components, factories, controllers, and directives in an Immediately Invoked Function Expression (IIFE). This is to prevent variables and functions polluting the global namespace.
  2. Use named functions instead of anonymous functions to help with debugging (generally a good idea for all JavaScript)
  3. Use the ControllerAs syntax to get access to this from the controller instead of using $scope. This is to avoid the “dot problem” in the views. It is also a good idea to assign this to a consistent variable such as VM to avoid this scoping issues.
  4. Use $inject to list all dependencies in an array for the component to prevent minification mangling, and huge function declarations including dependencies can be hard to read.

The whole document is a great read though and I really encourage you to read it if you are working on an Angular project.

LiveReload With Gulp

I’ve started working on a project to learn and use ES6 Modules, Angular and Gulp, and one of the first issues I encountered was getting LiveReload to work, refreshing my browser every time I changed a file. For those not familiar with the concept, LiveReload works in one of three ways (from the LiveReload FAQ):

To communicate with your browsers, LiveReloads needs its JavaScript code to be injected into your web pages. There are 3 ways to arrange that:

  • either add a script tag into your HTML code manually, or
  • install a browser extension (that, when activated, adds the script tag to the visited pages on the fly), or
  • use a plugin for your web framework (that adds the script tag on the fly when serving requests).

(more…)

Writing and Programming, Crafts Worth Honing

I’ve been doing quite a lot of writing lately, and quite a lot of thinking about writing, and a fair bit of reading too. This of course was one of my goals for 2015, and I’ve been keeping a consistent journal for the first time ever (fourteen days straight and counting). From all of this writing there is one thing I’ve come to realize and it’s that writing begets writing. The more you write, the better you become at clearly expressing your thoughts and ideas through writing and translating them from the jumble in your head to the written word. Your fingers fly across the keyboard with very little barrier between your mind and the keys.

As Joel Spolsky once said,

Writing is a muscle. The more you write, the more you’ll be able to write.

I’ve found that this is a truth in software engineering as well. When you are working with the same language every day you quickly get a lot better at expressing concepts and building elegant implementations through a lot of practice and Rote learning.

However, as is the case with writing, this can only get you so far. To truly hone each craft, and yes I consider programming and writing very similar crafts, you need to start to focus on different things if you are to further improve your craft.

For a software engineer, this might mean learning a new language or framework. There are a whole lot of them out there to choose from, take your pick! Or thinking of an idea for an app or tool, making it, and shipping it! Or even researching different concepts and APIs in your current language of choice, to get a new take on it and learn more about the tools that you have available to you.

For a writer, this can mean writing in different genres or from different points of view. It can mean writing in different formats. Have you ever written poetry, a long form essay, started a blog or written a journalistic piece? As with software engineering, you need to start thinking, really thinking about what you are doing, practice hard and push your own boundaries to really start getting good.

I compare these two crafts because the 10,000 hour rule is applicable to both. Each craft requires careful, deliberate practice for the engineer or writer to improve and become and expert at what they do. And if you really have a passion for something, you will bend every ounce of your will to perfecting that craft because you always get joy out of learning more from it.

Developing a craft is about dreaming big, and thinking deliberately about how you can improve. But you can’t let either of these things stop you from honing your craft. Dreams can stay as just that, dreams, or they can turn into a bestselling novel or highly successful company. Thoughts can stop you from ever accomplishing anything, from ever writing a line of code or setting pen to page. I think Rudyard Kipling had the right idea in his poem If:

If you can dream — and not make dreams your master;
If you can think — and not make thoughts your aim;

Writing is simple. Just write. Coding is simple. Just code. The rest is practice, practice, practice, passion, perseverance and a little bit of luck. Hone your craft, and love what you do.