Monthly Archives: October 2016

Three ways of understanding Promises

By Axel Rauschmayer

This blog post covers three ways of understanding Promises.

This is an example of invoking a Promise-based function asyncFunc():

    function asyncFunc() {
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve('DONE'), 100);
    .then(x => console.log('Result: '+x));

So what is a Promise?

  • Conceptually, invoking asyncFunc() is a blocking function call.
  • A Promise is both a container for a value and an event emitter.

Conceptually: calling a Promise-based function is blocking

    function asyncFunc() {
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve('DONE'), 100);
    async function main() {
        const x = await asyncFunc(); // (A)
        console.log('Result: '+x);
        // Same as:
        // asyncFunc()
        // .then(x => console.log('Result: '+x));

main() is an async function. Its body expresses well what’s going on conceptually – how we usually think about asynchronous computations:

  • Line (A): Wait until asyncFunc() is finished.
  • Line (B): Then log its result x.

Prior to ECMAScript 6 and generators, you couldn’t suspend and resume code, which is why, for Promises, you put everything that happens after the code is resumed into a callback. Invoking that callback is the same as resuming the code.

A Promise is a container for an asynchronously delivered value

If a function returns a Promise then that Promise is like a blank into which the function will (usually) eventually fill in its result, once it has computed it. You can simulate a simple version of this process via an Array:

    function asyncFunc() {
        const blank = [];
        setTimeout(() => blank.push('DONE'), 100);
        return blank;
    const blank = asyncFunc();
    // Wait until the value has been filled in
    setTimeout(() => {
        const x = blank[0]; // (A)
        console.log('Result: '+x);
    }, 200);
    // Output:
    // Result: DONE

With Promises, you don’t access the eventual value via [0] (line (A)), you use method then() and a callback.

A Promise is an event emitter

Another way to view a Promise is as an object that emits events.

    function asyncFunc() {
        const eventEmitter = { success: [] };
        setTimeout(() => { // (A)
            for (const handler of eventEmitter.success) {
        }, 100);
        return eventEmitter;
    .success.push(x => console.log('Result: '+x)); // (B)

Registering the event listener (line (B)) can be done after calling asyncFunc(), because the callback handed to setTimeout() (line (A)) is executed asynchronously, after this piece of code is finished.

Normal event emitters specialize in delivering multiple events, starting as soon as you register.

In contrast, Promises specialize in delivering exactly one value and come with built-in protection against registering too late: the result of a Promise is cached and passed to event listeners that are registered after the Promise was settled.

Further reading

Source:: 2ality

Angular 2 ngFor

By John Papa

Angular 2 ngFor

Have you tried ngFor in Angular 2? I bet you have. If you try the Angular 2 release candidate or later, you may have noticed a pervasive change that affects nearly every early adopter of Angular 2. The syntax changed very subtly.

The new syntax is super easy to refactor. However being inquisitive like we are, my friend Ward Bell and I wondered why it was made. This post helps explain why the late change happened based on our perceptions.

Most of this post came directly from my friend Ward’s thoughts. I suggested it was awesome and useful information and requested he let me post it. He agreed. And here we are 🙂

Overview of *ngFor and ref-

Here are the changes to the micro-syntax for ngFor.

  • We now use let item of items instead of #item of items inside *ngFor.
  • Outside of *ngFor, replace all var-x with ref-x

The terminology also subtly changed. What we used to call a local template variable is now either a template input variable (inside *ngFor) or a template reference variable (outside *ngFor).

The new *ngFor micro-syntax

Before beta.17 we wrote:

<div *ngFor="#hero of heroes; #i=index">  
  {{i + 1}} - {{hero.fullName}}

After beta.17, and including the RC’s, we write:

<div *ngFor="let hero of heroes; let i=index">  
  {{i + 1}} - {{hero.fullName}}

The migration path is as simple as replacing #xxx with let xxx.

The old way will continue to work for a while longer. But it has been deprecated as you can see in a console warning message such as this:

"#" inside of expressions is deprecated. Use "let" instead! ("
<div [ERROR ->]*ngFor="#hero of heroes">{{hero}}</div>  
"): StructuralDirectivesComponent@7:5

Why the change?

Outside of *ngFor, a variable preceded by # defines a template reference variable, typically a reference to an element in the DOM.

<input #heroBox >  

The heroBox variable is a reference to the input box and we can use it to display its value property.

That’s not what the hero variable does inside the *ngFor.

<div *ngFor="let hero of heroes; let i=index">{{i + 1}} - {{hero.fullName}}</div>  

That hero variable is not a reference to the

It is actually an input to the (invisible) Angular function that repeats the

for as many times as there are heroes in the list.

It’s a different kind of variable, what we now call a template input variable.

We can’t and shouldn’t use the same syntax for both a template input variable and a template reference variable.

Thus the change was made.

let x means that x is a template input variable in an *ngFor.

#x means that x is a template reference variable that usually references a DOM element; it cannot be used within an *ngFor.

Use ref-, not var-

Before beta.17 we could write #x as var-x; this was an alternative syntax for those relatively few developers who prefer a prefix to the (#) symbol.

The var-x syntax is now illegal. Starting in beta.17, we must write it as ref-x in keeping with the new, clearer term: template reference variable.

Source:: johnpapa

Angular 2 Workshop in Barcelona

By John Papa

Angular 2 Workshop in Barcelona

Are you interested learning Angular 2? Come join myself and Dan Wahlin on July 31st in Barcelona, Spain for a fun filled and content rich exploration of Angular 2!

Angular 2 Workshop in Barcelona

  • What? Learn Angular 2
  • Where? University of Barcelona
  • When? July 31, 2016
  • Who? Learn from Dan Wahlin and John Papa
  • Register here and Use code PAPA for € 100 off for the early bird discount

Dan Wahlin and I will be in Barcelona for a full day of Angular 2 and look forward to sharing our knowledge, expertise and passion with everyone.

Registration opens Tuesday, May 17th … please check back on this site or check Twitter for the registration link. Space will be limited and there will be an early bird special rate for the workshop.

Workshop Details

Whether you’ve been building Angular 1 applications or you’re brand new to Angular, this workshop will provide a ground-up approach to learning Angular 2 concepts and by the end of the day you’ll understand how all of the “pieces” fit together.

The workshop explores the core concepts that will help you build end-to-end Angular 2 solutions including the role of ES6/TypeScript, project setup, code structure, style guide, using the Angular CLI, data binding and MV*, abstracted remote data calls through services, observables, and routing.

You’ll experience several demos and be provided with the code throughout the workshop, as you learn how to build apps using Angular 2.

Workshop Agenda

We’ll explore and learn:

  • Why use Angular 2?
  • ES6/TypeScript fundamentals
  • Transpiling/compiling TypeScript to JavaScript
  • Getting started with the Angular CLI
  • Bootstrapping your application
  • The Role of Components
  • Using Decorators in Components (metadata)
  • Dependency injection and providers
  • Binding data to views
  • Input and output properties
  • Managing remote data calls using services
  • Http and RxJS Observables
  • Routing and page navigation

If you’re looking to get a jump start on Angular 2 and learn how you can build robust apps, then come join us for a day of learning and fun!

Bring your laptops, as we’ll include some “code along with us” activities.

Whenever Dan and I get together we have a great time. We hope you can join us!

Special thanks to Angular Beers, for sponsoring us
Angular 2 Workshop in Barcelona

Source:: johnpapa

17 Minute Angular 2 App

By John Papa

17 Minute Angular 2 App

Last week I had the privilege of coding an Angular 2 app in front of the live audience at the 3rd annual ngConf event. I had a lot of fun and, perhaps luckily, I didn’t make any major mistakes 🙂 More importantly, I believe this session shines a light on the seven most fundamental aspects that we need to build an Angular 2 app.

  1. Modules
  2. Components
  3. Templates
  4. Data Binding
  5. Structural Directives
  6. Services
  7. Dependency Injection

Watch the video of my session, An Angular 2 Force Awakens, here.

If you enjoyed this, please join me and Dan Wahlin at our full day Angular 2 workshop in Barcelona in July.

We all love tools that help use code more efficiently, so stick around for the end where I rapid fire some tools you will want to check out. Some of these include snippets, a CLI, and the official Angular 2 Style Guide.

The formal session description is shown below:

There’s been an awakening in the Web. Angular 2 has arrived and it’s time to learn the key features that help you successfully build Angular 2 apps. We’ll create an Angular 2 app from scratch, add components to track Star Wars characters, and configure routing between the views. The data may be needed throughout the app, so we’ll create a shared service and use dependency injection to access it from the components. We’ll also cover accessing data via HTTP, using metadata to describe components, and the new templating and data binding concepts in Angular 2. You may not walk out a Jedi, but the you will feel the power of the force.

You can find the source code here and the slides here.

17 Minute Angular 2 App

Source:: johnpapa

Multiple Versions of Node with n

By John Papa

Multiple Versions of Node with n

What happens when a new version of node is released? What if you need version 0.10.36 for one app and 4.4.2 for another? Did you know version 6 is out now too? Yikes! it would be great if we could manage multiple versions of node on the same computer.

Well, we can with n or nvm!

These are 2 different tools that allow us to host multiple versions of node. We can use it to select which version to activate, and the toggle back to another version in seconds. They are super helpful.

I prefer n, but it only works on a Mac. We can install it by running npm i -g n. Simply run n 4.4.2 and it will install that version. Watch this clip to see it in action.

Multiple Versions of Node with n

Learn more about how to toggle between versions or install new versions of node from n‘s docs

If you run on Windows, nvm is very similar. In fact, nvm runs on Mac and Windows.

Either way you choose, these are vital tools for every node developer.

Source:: johnpapa

Why Angular 2 ? A Rapid Fire Q&A Session

By John Papa

Why Angular 2 ? A Rapid Fire Q&A Session

Why should we be using Angular 2? What’s all the chatter about? It can be difficult to keep up with the fast paced Web, so we all need tools to help us filter out the noise and focus on the things that add value. That was our intention behind this webcast on Angular 2 from Pluralsight.

We had such a large attendance that we all nearly broke the webcasting tool. Seriously. OK, so that never should have happened, but lesson learned.

Not to worry, though. We covered a lot of ground on why we should all be looking at Angular 2 and some extremely valuable tools like the Angular 2 style guide, code snippets, CLI, and codelyzer.


When it was time to start the Q&A session, I opened the question list from the attendees and there were over 1000 questions! Therefore I began a wickedly fast paced Q&A at the to cover as many of them as I could get to :).


If you missed the Angular 2 webinar, or just want to watch it again, you can do so here.

We also included a links to all of the resources including the tools above, my latest Angular 2 course, and a free live coding demo from ng-conf!

Original Webcast Description …

There’s been an awakening in the Web. Angular 2 has arrived and now’s the time for you and your tech team get on board. Learning the key features to help you successfully build Angular 2 apps can dramatically transform the way your developers tackle large-scale projects. Knowing where to start, which projects you should begin with and how to get your tech team started on an epic journey.

Join Pluralsight author, John Papa, in this live webinar, where we’ll create an Angular 2 app from scratch and add components to track Star Wars characters.
The data may be needed throughout the app, so we’ll create a shared service and use dependency injection to access it from the components. We’ll also cover accessing data via HTTP, using metadata to describe components and the new templating and data binding concepts in Angular 2. You may not walk out a Jedi, but you will feel the power of the force.

Source:: johnpapa

Step Back and Ask Why

By John Papa

Step Back and Ask Why

Solving deep technical problems is fun. But by taking a step back and examining how we got here can be just as fun and useful.

We pride ourselves on our technical abilities. But an even more important skill we can have is not technical, it is a pragmatic skill: we can ask “why?”.

Why is such a simple word but it helps us evaluate how we got this our current point. What decisions did we make? What influenced us? Has any of the information changed since then? Did we miss a perspective or an option?

I find that this skill, when used with empathy, respect, and patience, proves its value repeatedly. The value is in uncovering new options or in reinforcing the direction we already traversed.


Have you heard one of these before? “This component is just so complex it requires all 2000 lines of code.” … or how about … “We can’t write unit tests for this code.”

Over the years I’ve heard these often. The interactions usually go something like this with a developer team. And sometimes I’m the one helping, and sometimes I am the one receiving the help 🙂

Me: Why don’t you have tests for this component?

Team: This component is just so complex that we can’t test it.

Me: Why is it so complex?

Team: The business rules have many variations and branches. Also, there are many rules we have to go get other data so we can make decisions.

Me: Why do the rules and data all have to be in this one component?

Team: Well, they don’t but the code is very intertwined. Perhaps we could pull out the data calls.

Me: Good idea. Why do all the branches exist?

Team: The branches help decide the course of action.

Me: Do those decisions have to be made in other places too?

Team: Yes, in some cases. We can break those out into services too.

Me: How do you keep up with the complex logic?

Team: We write tons of comments.

Me: Are the comments all correct?

Team: No, the accuracy is difficult to maintain.

Me: Have you tried moving that complex logic to a function named for what it does?

Team: No, but let’s try that now!


These types if interactions are trimmed down a bit, but usually they take anywhere from five to 20 minutes. Let me be clear … these are all with very intelligent and accomplished teams. And sometimes I have been the one on the receiving end of this (and grateful for the help). We don’t always see every angle. We sometimes make assumptions that cause us to miss things.

These types of retrospectives can help illuminate the options.

Open the Code and Refactor

Sometimes I open the code and start refactoring with them. One time in particular I recall a team pushing me out of the way about ten minutes into the conversation and refactoring the code themselves. This was the best result possible, IMO. This was a super bright team who just needed a gentle nudge in the right direction and then they were off and running.

I find that opening the code and doing it with a team via pair programming is a very productive way to help solve problems. The best part is when you hand over the keyboard and the net result is code that is:

  • maintainable
  • readable
  • has less or no comments

And my favorite part is that often there are less lines of code overall. It is pretty darn cool when we can accomplish all of this by refactoring our code to be better and have deleted more lines than we write!

Smaller Bites of Shareable Code

Moving code into smaller and more digestible functions make it easier to read, share and test our code. Take any large function and we usually find several conditionals, guard logic, calculations, formatting, and then some final action which returns a value. Try this exercise and break down the function. We may have already done this if we see lots of comments explaining the steps the function takes. (more on comments in a moment).

Now take those individual steps inside the function and replace them with smaller functions. Now our function goes from being a long function doing many things to a series of smaller functions, each doing one specific job. We’ve now reduced our the responsibilities of each function and made it easier to test, share, and read.

Here is a great example of how we can split up a file that does many things into smaller units.

Replace Comments with Named Functions and Variables

We can take comments and replace them with a function. Why? Consider a comment on some logic that explains how to check for the customer’s credit. Why not replace that comment with a function named let credit = checkCustomerCredit(customer) ? Or better yet, let’s move that logic to a customer service and do this let credit = customer.checkCredit();. Now we move logic to a more testable and shareable state and we remove the need for comments.

OK, so making it shareable is an easy win, but I often run into remarks like “comments make my code more readable”. Sometimes they do when used for things that are reporting consequences for things that are not obvious or for TODO’s. But the vast majority of the time we can remove comments and replace with variables and functions that make sense and are readable.

This has the added advantage of making our code keep us honest. How? The comment is not a runnable line of code. It is easy for it to become incorrect. If we use a variable name or function name, it helps keep us honest.

Have Courage

Don’t be afraid to step back and re-look at the problem. Why are we here?

It is easy to hide in the weeds of the problem, but it’s an even better idea to step back and consider a few questions:

  • are we addressing the right problem?
  • is this going to help us achieve our story?
  • is the priority of this important?
  • have we considered all angles?
  • why did we toss aside these other options?
  • if someone else looked at my code, would it make sense to them?

It’s OK to re-think. It’s OK to make changes. It’s OK to ask for a second set of eyes. Of course we all have deadlines, so we don’t spend days on this … but we can do ourselves and our team an injustice if we focus on the trees for the forest, instead of the other way around.

Every once in a while stop. Ask why.

Source:: johnpapa

Angular 2 QuickStart with Ward Bell

By John Papa

Angular 2 QuickStart with Ward Bell

Recently I had a great opportunity to sit down with my good friend and expert Angular developer Ward Bell to film a Play by Play for Pluralsight on Angular 2. You can watch Ward and I build an Angular 2 app from scratch, and see us explaining the decisions we make as the code unfolds.

Here is the description of the video with us …

In this video, Curious about getting started in Angular 2? This Play by Play will get you up and running in under two hours. In this course, Angular experts John Papa and Ward Bell build an Angular 2 app from scratch. You’ll learn about the various options for spinning up an Angular 2 app, including the Angular 2 QuickStart on Github. Once installed, you’ll see John and Ward add test coverage (and learn why Ward insists on end-to-end testing), work through building components, data binding, dependency injection, and handling HTTP requests. Along the way, you’ll learn best practices from two Angular masters, and valuable tips that will help you write better code and take advantage of powerful Angular features. By the end of this course, you’ll have a solid launching point for building Angular 2 applications of your own.

The code used in the demonstration is available at

Source:: johnpapa

The Ultimate Angular 2 Workshop in Ft Lauderdale

By John Papa

The Ultimate Angular 2 Workshop in Ft Lauderdale

Angular 2’s engineering makes it extremely powerful for web and mobile applications. It is a great time to learn how to build apps with Angular 2 using Dependency Injection, providers, data binding, RxJS, Components, Modules, Services, and more!

I’m excited to announce a new two day Ultimate Angular 2 Workshop that is custom tailored to jump starting into Angular 2, hosted by myself and my friend Dan Wahlin in Ft Lauderdale, Florida on October 6 and 7!

Register now

(The EARLY bird discount code expires on Sep 2, 2016)

Interested in learning how to build applications with Angular 2? Whether you’ve been building Angular 1 applications or you’re brand new to Angular, this workshop will provide a ground-up approach to learning Angular 2 concepts.

The workshop explores the core pieces that help you build end-to-end solutions including the role of ES6/TypeScript, project setup, code structure, using data binding and MV*, abstracted remote data calls through services, routing, and modules. Bring your laptop as you’ll learn through demos and hands-on coding along with Dan and John throughout the workshop that will help you learn and understand the Angular 2 framework. All slides and code samples are yours to keep.

Topics that this workshop covers include:

  • SPA fundamentals
  • Importance of Separation of Concerns (SoC)
  • ES6/TypeScript fundamentals
  • Built-in Types, Enums, Functions
  • Optional, Default and Rest Parameters
  • Arrow Functions and “this”
  • Classes, Interfaces and Decorators
  • ES6 Modules in TypeScript
  • Bootstrapping your application
  • The Role of Components
  • Using Annotations in Components
  • Dependency injection
  • Binding data to views
  • Working with forms
  • Managing remote data calls using services
  • Routing and page navigation
  • Separation with NgModules
  • Organizing your code and Style Guide recommendations
  • Lazy Loading of modules
  • Debugging TypeScript and Angular 2

Source:: johnpapa

Learning Angular 2 this Fall

By John Papa

Learning Angular 2 this Fall

Modern Web development techniques keep moving forward: Angular 2, RxJS, TypeScript, ES2016/2017. It can be daunting to keep up with the constant progression of web technology, but it is also very much worth it as what we can build also improves.

It is a great time to learn how to build apps with Angular 2 using Dependency Injection, providers, data binding, RxJS, Components, Modules, Services, and more!

If you are looking to learn the modern Web techniques with Angular 2, ES2016/ES2017, TypeScript and more you can catch one of the many events coming this Fall. Here are several events I’ll be at, and some discount codes (where applicable).

I hope to see you at one of these!

Ultimate Angular 2 Workshop

October 6 and 7, Ft Lauderdale, Florida

An immersive two day Angular 2 hands-on workshop that is custom tailored to help you jump start your skills with Angular 2, hosted by myself and my friend Dan Wahlin.

Register now

Microsoft Ignite

September 26-30, Atlanta, Georgia

Microsoft’s large annual event that covers a wide breadth of technologies. I’ll be presenting a session on Angular 2 with TypeScript and Visual Studio Code. Also, be sure to check out the mobile technology panel with several mobile experts that I will be moderating.

Microsoft Ignite


October 24-28, Las Vegas, Nevada

This event is all about the Web, and it’s a great place to learn where the Web is heading from some great leaders in our industry. It is co-located with DevIntersections, a Microsoft technology event, so you get 2 events for the price of one.

I’ll be co-presenting sessions on TypeScript, ES6, and Angular 2 with my friend Dan Wahlin as well as some workshops on the same topics.

Register here with discount code PAPA

VS Live

December 5-9, Orlando, Florida

This event covers the gambit of Web and Microsoft technology. I’ll be presenting a session on TypeScript and ES6 as well as a one day workshop on Angular 2.

Register here and save up to $500 with this discount code LSPK63

Source:: johnpapa