Monthly Archives: October 2016

Introducing Angular Modules - Root Module

By John Papa

Introducing Angular Modules - Root Module

The @NgModule is a new decorator that has recently been added in Angular 2. NgModule defines an Angular Module, which (from the official docs) are defined as “Angular Modules help organize an application into cohesive blocks of functionality.”

This post introduces @NgModule and its most oft used features when creating a root module. Angular Modules can also assist with separation of features, and eager and lazy loading of those features. I’ll explore these in future posts, but first we must grasp the basics and create a simple root module.

I’m currently updating my Angular 2 First Look course on Pluralsight for this and other new topics. Be sure to check back later this Fall.

Angular Modules Series

  1. Introducing NgModule and the Root Module
  2. Routing Module
  3. Feature Modules
  4. Shared/Core Modules
  5. Eager and Lazy Loading

Simple Root Module

We use an Angular Module as the starting point for our applications. When we decorate a class with @NgModule we are telling Angular important information about this Angular Module’s role.

// app.module.ts
@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule { }  

First, we declare that the AppComponent belongs to the AppModule by setting the AppComponent in the declarations property. Our AppComponent may have a selector of my-app. When Angular sees my-app in the template it will now recognize it.

Every app starts somewhere. By convention our apps start at AppModule. This is our root module and thus we advise Angular that when it creates AppModule at start that we want to bootstrap AppComponent into the DOM.

We import modules that our Angular Modules will use. In the example above we import the BrowserModule which registers important application service providers for running in the browser. BrowserModule includes built-in directives like NgIf and NgFor. This means we can use these built-in directives in any of this module’s component templates.

Introducing Angular Modules - Root Module

Bootstrapping our App

We start our applications using main.ts, file by convention (see the style guide).

The example below shows how we will bootstrap AppModule using the browser platform. Again, by convention, we name the AppModule file app.module.ts.

// main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
import { AppModule } from './app.module';  
platformBrowserDynamic().bootstrapModule(AppModule);  

This uses the Just in Time (JIT) compilation. We can use Ahead of Time (AOT), but that is a topic for a future post.

Declaring

We create custom components, directives and pipes in our application. We can tell Angular that this module will use these by declaring the in the @NgModule declarations property.

// app.module.ts
@NgModule({
  imports: [BrowserModule],
  declarations: [
    AppComponent,
    VehicleListComponent,
    VehicleSelectionDirective,
    VehicleSortingPipe
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }  

Imports

We imported BrowserModule, which itself imports the CommonModule which contains the common built-in directives such as NgIf and NgFor. By importing BrowserModule, we in turn get what CommonModule has to offer too.

What if we want to use form functionality such as ngModel or http? We can import those modules, too. This makes these features available in or AppModule.

// app.module.ts
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  declarations: [
    AppComponent,
    VehicleListComponent,
    VehicleSelectionDirective,
    VehicleSortingPipe
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }  

Now that we have imported FormsModule, we can use ngModel in our templates. When we use http to get or post data since we imported HttpModule.

Providers

We often have services that we want to share within our app. How do we allow all of our components to use a service? We use Angular Modules.

We can add add providers to the application’s root dependency injector in our AppModule. Since our AppModule is our root module, this will make the services available everywhere in the application.

Some ideal examples of services we want to make available across the board are be a user profile service or a logging service. Our app also shows a list of vehicles, so we might have a VehicleService to retrieve those using http (which we can use because we imported the HttpModule).

// logger.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class LoggerService {  
  log = (msg: string) => {
    console.log(msg);
  };
}
// vehicle.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class VehicleService {  
  getVehicles = () => [
    { id: 1, name: 'X-Wing Fighter' },
    { id: 2, name: 'Tie Fighter' },
    { id: 3, name: 'Y-Wing Fighter' }
  ];
}

When we provide these services to the AppModule they are available to our declared components.

// app.module.ts
@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule],
  declarations: [
    AppComponent,
    VehicleListComponent,
    VehicleSelectionDirective,
    VehicleSortingPipe
  ],
  providers: [
    LoggerService,
    VehicleService,
    UserProfileService
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }  

When a component tries to inject a service in its constructor, it is asking Angular to find that service. In this sample with our root app module, Angular first looks in this component’s (VehicleListComponent) injector for our service. Since we did not provide the service in the @Component decorator’s providers property, Angular keeps going up the component tree until it finds the service. We never provided it in a component, so it ultimately looks in its root injector and finds our service. If the service has already been instantiated, we get that service instance. If not, a new instance is created. This is how we locate and inject services.

Providers are perhaps one of the most involved and challenging Angular Module concepts. For a general rule of thumb, provide services you intend to be shared across your app, as a single multi-use instance, in the app root module.

What Else?

Using these concepts we can get started with Angular Modules. But when our app grows, how do we know when and where to create new Angular Modules for our feature areas? How do they related to one another? How do we make sure services are instantiated as singletons or multiple instances? How do we decide if code should be eager or lazy loaded? These are topics for future posts now that we know basic building blocks of Angular Modules.

Ultimate Angular 2 Workshop

If you want to learn more about Angular 2 and NgModule, come join Dan Wahlin and I at the Ultimate Angular 2 Workshop on October 6 and 7, in Ft Lauderdale, Florida

This is an immersive two day Angular 2 hands-on workshop that is custom tailored to help you jump start your skills with Angular 2.

Register now

Source:: johnpapa

Introducing Angular Modules - Routing Module

By John Papa

Introducing Angular Modules - Routing Module

The @NgModule is a new decorator that has recently been added in Angular 2. NgModule defines an Angular Module, which (from the official docs) are defined as “Angular Modules help organize an application into cohesive blocks of functionality.”

This post is the second in a series that introduce @NgModule and its role in creating Angular 2 apps. In this post I’ll discuss some motivations for creating multiple modules, some decisions we have to make regarding them, and how routing fits into modules.

Angular Modules Series

  1. Introducing NgModule and the Root Module
  2. Routing Module
  3. Feature Modules
  4. Shared/Core Modules
  5. Eager and Lazy Loading

I’m currently updating my Angular 2 First Look course on Pluralsight for this and other new topics. Be sure to check back later this Fall.

One Root Module

When we create an Angular 2 app, we define a root module. We learned about this in the previous post. This root module is defined with @NgModule and works quite well for small apps.

// app.module.ts
@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule],
  declarations: [
    AppComponent,
    VehicleListComponent,
    VehicleSelectionDirective,
    VehicleSortingPipe
  ],
  providers: [
    LoggerService,
    VehicleService,
    UserProfileService
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }  

Our root module declares our components, pipes and directives so Angular can recognize them in our templates. Our root module imports common features from the Angular 2 BrowserModule, FormsModule, and HttpModule. This allows us to use common features like ngIf and ngFor, ngModel for forms, and the Http service in our app. We’re pretty set right now on basic functionality.

Our root module also provides a few custom services. Because we do this in the root module, anyone in our current app can use these.

We could continue to add more components and features to this root module, and it would work. But at some point we may want to organize our app by related features. Perhaps we have a vehicles feature, an characters feature, a login feature, and a reusable widgets feature. Each of these feature areas may have multiple components and it might make sense to keep them together.

Why Create More Modules?

But Why? Why keep the features together? Why encapsulate the features? One reason is organization and readability.

A more technical reason is that we may want to make a feature promotable. For example a we could make a feature that has custom widgets such as a CalendarComponent and ButtonComponent. We may want to use these across the entire app and intend to use them in other apps. Making a feature area for these widgets makes a lot of sense in this case.

Another reason for encapsulating feature areas is to help keep the starting app lean and fast. When the app starts we may want to only send the parts of the app that are needed to crank it up and are the most commonly used pieces. That may not include all feature areas. The ones we want to load up front could be eagerly loaded while the others could be lazily loaded as needed.

All of these are made easier by @NgModule.

Expanding Our App with Features

Let’s warp speed forward a bit and our app now has some of these features. We would likely start by putting all of these in the root module, and it might end up looking something like the following.

// app.module.ts
@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule],
  declarations: [
    // Root Feature
    AppComponent,
    NavComponent,

    // Widgets Feature
    ButtonComponent,
    DateComponent,

    // Character Feature
    CharactersListComponent,
    CharactersDetailComponent,

    // Vehicle Feature
    VehicleListComponent,
    VehicleSelectionDirective,
    VehicleSortingPipe
  ],
  providers: [
    LoggerService,
    VehicleService,
    UserProfileService
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }  

Notice our declarables got quite a bit larger. That’s ok … now let’s step aside and look at another requirement of most apps: routing.

Routing in a Module

Our app has many features and we want to use routing to navigate between our components. We also have a NavComponent that the allows the user to navigate. We’re going to need to add routing logic to our app.

// app.routing.ts
import { NgModule } from '@angular/core';  
import { Routes, RouterModule } from '@angular/router';  
import { CharactersComponent } from './characters/characters.component.ts';  
import { VehiclesComponent } from './vehicles/vehicles.component.ts';

const routes: Routes = [  
  { path: '', pathMatch: 'full', redirectTo: 'vehicles' },
  { path: 'vehicles', component: VehiclesComponent },
  { path: 'characters', component: CharactersComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule { }

export const routingComponents = [VehiclesComponent, CharactersComponent];  

Here we created an app.routing.ts file that exports AppRoutingModule which is … wait for it … an Angular module!

Notice how we are explicitly referencing the components in the routes? These are currently set up for eager loading. We can make them load on demand (aka lazy loading) … we’ll learn more about that in a future post.

We just discovered another reason to create modules. We can now import this module into our root module.

// app.module.ts
//...
import { AppRoutingModule, routingComponents } from './app.routing';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  declarations: [AppComponent, routingComponents],
  providers: [VehicleService],
  bootstrap: [AppComponent]
})
export class AppModule { }  

Importing the routing module we created also gives us the routing features we need. That forRoot() function returned a module, which is imported by AppRoutingModule, which in turn is imported in the root module.

The forRoot() function should only be used for creating the root modules’ routes. When we get to child modules and routes, we’ll use other techniques that we’ll see in later posts.

Here is a simple example of an app with a root module and a routing module.

Introducing Angular Modules - Routing Module

More Modules?

We just took the first steps to creating more modules, for our features. Along the way we created a routing module and imported it. If we want to organize our app by feature, promote our widgets, and load features as we use them it may benefit us to encapsulate the features. We’ll do this by creating more modules in the next post.

Ultimate Angular 2 Workshop

If you want to learn more about Angular 2 and NgModule, come join Dan Wahlin and I at the Ultimate Angular 2 Workshop on October 6 and 7, in Ft Lauderdale, Florida

This is an immersive two day Angular 2 hands-on workshop that is custom tailored to help you jump start your skills with Angular 2.

Register now

Source:: johnpapa

Introducing Angular Modules - Feature Modules

By John Papa

Introducing Angular Modules - Feature Modules

The @NgModule is a new decorator that has recently been added in Angular 2. NgModule defines an Angular Module, which (from the official docs) are defined as “Angular Modules help organize an application into cohesive blocks of functionality.”

This post is the third in a series that introduce @NgModule and its role in creating Angular 2 apps. In this post I’ll discuss some motivations for creating feature modules.

Angular Modules Series

  1. Introducing NgModule and the Root Module
  2. Routing Module
  3. Feature Modules
  4. Shared/Core Modules
  5. Eager and Lazy Loading

I’m currently updating my Angular 2 First Look course on Pluralsight for this and other new topics. Be sure to check back later this Fall.

Features

Often our apps have discrete sets of related functionality. Customers, orders, administration, and login/logout are all examples of areas of our apps that, when linked together, make our app. Basically, we break down our app into smaller pieces. Let’s refer to these pieces as features.

It makes sense that some of these features have functionality that is not intended to be exposed outside of the feature. We also may want to add a feature to the app as a whole unit at a later time. Or maybe the feature is there and we want to lazy load it when the user decides it is time to visit the feature.

These are all reasons why we might want to divide our app into feature areas. Many technologies have this concept in different forms. Angular 2 addresses this with @NgModule.

Identifying Features

Let’s revisit where we last left our app by looking at its root module. Notice that we have various components in our declarations. This could easily grow to a long list in even a medium sized app. But also notice that many of these declarations can be logically grouped together. These are candidates for features.

// app.module.ts
@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule],
  declarations: [
    // Root Feature
    AppComponent,
    NavComponent,

    // Shared Widgets Feature
    ButtonComponent,
    DateComponent,

    // Character Feature
    CharactersListComponent,
    CharactersDetailComponent,

    // Vehicle Feature
    VehicleListComponent,
    VehicleSelectionDirective,
    VehicleSortingPipe
  ],
  providers: [
    LoggerService,
    VehicleService,
    UserProfileService
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }  

We identify features by first looking for sets of components, pipes, directives, and services that related to each other. Then if these are not used by other places, it becomes a stronger case for a feature module. Let’s examine each.

Our root module makes sense for our AppComponent and NavComponent. These are needed everywhere in our app visually and for logic. They are also needed as soon as our app is loaded. If we had a lot of declarations that fit this description of NavComponent we might consider creating another feature too, for navigation. But with only one, we can leave it in the root module.

Shared Features

Our ButtonComponent and DateComponent are widgets that we will use in many places across our app. We want to make multiple instances of them and for these to be available everywhere. We could leave these in the root module, just like we did for the NavComponent. However, these are slightly different in that we intend to use these many times over, with multiple instances appearing the a component. We very likely will have many other widgets, so this list will grow. These shared components are a logical place to create a SharedModule as a feature module.

Let’s create a new @NgModule for this feature.

// app/shared/shared.module.ts
import { NgModule } from '@angular/core';  
import { CommonModule } from '@angular/common';  
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [CommonModule, FormsModule],
  exports: [
    CommonModule, FormsModule,
    ButtonComponent, DateComponent
  ],
  declarations: [ButtonComponent, DateComponent]
})
export class SharedModule { }  

Notice the @SharedModule declares the components and also exports them. Exporting them allows others to use those components, which we intend to do in our app’s templates.

We modify the root module to no longer declare these shared components and instead we import the SharedModule. This becomes very useful when our app grows to have 5, 10 or more shared components.

Our components in the root module can still use DateComponent and ButtonComponent in their templates.

// app/app.module.ts
@NgModule({
  imports: [
    BrowserModule, FormsModule, HttpModule,
    SharedModule // Shared feature
  ],
  declarations: [
    // Root Feature
    AppComponent,
    NavComponent,

    // Character Feature
    CharactersListComponent,
    CharactersDetailComponent,

    // Vehicle Feature
    VehicleListComponent,
    VehicleSelectionDirective,
    VehicleSortingPipe
  ],
  providers: [
    LoggerService,
    VehicleService,
    UserProfileService
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }  

Characters Feature

We have another opportunity for creating a feature by grouping the characters. It is likely we will have more than two components plus some pipes or directives too. Sometimes in our apps we’ll identify these features are areas of an app where we route to. This is a very discrete feature area that we’ll make into a CharactersModule.

We already had routing for our characters in our root module’s app.routing.ts. Let’s move that to our new CharactersModule. We’ll create a folder for our feature module and a new file app/characters/characters.routing.ts. We’ll also remove these routes from the app.routing.ts. Effectively, we’re just moving the route setup for this feature area where it belongs.

// app/characters/characters.routing.ts
// ...

const routes: Routes = [  
  { path: 'characters', component: CharactersListComponent },
  { path: 'character/:id', component: CharactersDetailComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CharactersRoutingModule { }

export const routedComponents = [CharactersListComponent, CharactersDetailComponent];  

Notice we use the forChild() function here and not the forRoot(). When we create feature modules, we always use forChild() as the forRoot() function is reserved for the app’s root module.

Now that we moved routing, let’s create the feature module in app/characters/characters.module.ts. Notice it is pretty small as it imports the CharactersRoutingModule routing module we just created and declares the routedComponents. These are just a convention I like to use to grab a set of the routed components, instead of having to re-import each component, one by one.

// app/characters/characters.module.ts
// ...
@NgModule({
  imports: [CharactersRoutingModule, SharedModule],
  declarations: [routedComponents]
})
export class CharactersModule { }  

Our character feature’s component want to use the shared features including the ButtonComponent. Modules do no inherit each other, so even though the CharactersModule is going to be imported by the AppModule (which imports the SharedModule already), the CharactersModule cannot access the shared features … unless we import SharedModule.

Shared features modules must be imported by any module expecting to use it’s declarables.

Don’t worry though, if we forget to import the SharedModule Angular will throw an error telling us it does not recognize the ButtonComponent‘s template (e.g. my-button) when it sees it.

Now we refactor our app’s root module to import the feature and we remove the individual declarations of its components.

  // app.module.ts - revised
  @NgModule({
    imports: [
      BrowserModule, FormsModule, HttpModule,
      SharedModule, CharactersModule
    ],
    declarations: [
      // Root Feature
      AppComponent,
      NavComponent,
      // Vehicle Feature - soon!
      VehicleListComponent,
      VehicleSelectionDirective,
      VehicleSortingPipe
    ],
    providers: [
      LoggerService,
      VehicleService,
      UserProfileService
    ],
    bootstrap: [AppComponent],
  })
  export class AppModule { }

Feature Module Providers

Our app needs have changed a little and we need a service to gather a list of characters and get a single character for the CharacterListComponent and CharactersDetailComponent. We have to decide which module to put the service and where to provide it. Let’s think about how we should approach this.

We will only use our service by these two components. Therefore, it makes sense that we place our new CharactersService in the CharactersModule.

Now we have to decide where to provide the service. We can either provide it in a component or in its module. If we provide it in a component, we’ll need to do this in each component that uses it (for our example). Our list and detail components are separated and not in a parent-child association. If we had a parent component (which we could create) such as CharacterLandingComponent that had the other two as children, we could provide it there and the child components would be able to access it. This is due to how Angular’s injectors work. Angular injectors are hierarchical and exist at each component level. Clearly, this is a lot to think about 🙂

There is an easier way and one with more possibilities.

If we provide the CharactersService in the CharactersModule, it is accessible to all components in this module. The caveat to be aware of is that there is no module level injector … but there is one available at the root module.

When we provide a service in a feature module that is eagerly loaded by our app’s root module, it is available for everyone to inject.

We’ll provide the service in our eagerly module, thus making it available everywhere. We may not use it elsewhere, but it is available if needed.

// app/characters/characters.module.ts
// ...
@NgModule({
  imports: [CharactersRoutingModule, SharedModule],
  declarations: [routedComponents],
  providers: [CharactersService]
})
export class CharactersModule { }  

Introducing Angular Modules - Feature Modules

We’ll touch on providers more later. There is a great section in the Angular docs about this topic here.

Next

We learned how to make 2 different kinds of feature modules. We created a SharedModule which offers shared features that we’ll expect to use in lots of places with multiple instances. This is ideal for widgets or pipes. We also created a feature module for characters, which we route to and eagerly load.

In the upcoming posts we’ll explore how to reuse services across the app’s modules and how to lazily load our modules.

Ultimate Angular 2 Workshop

If you want to learn more about Angular 2 and NgModule, come join Dan Wahlin and I at the Ultimate Angular 2 Workshop on October 6 and 7, in Ft Lauderdale, Florida

This is an immersive two day Angular 2 hands-on workshop that is custom tailored to help you jump start your skills with Angular 2.

Register now

Source:: johnpapa

Onsen UI with Vue 2 will soon be possible!

By [object Object]

Onsen UI and Vue.js

Vue.js is a lightweight library used to create user interfaces. Its powerful but still intuitive API makes it very easy to learn. Vue has long been a favorite for us in the Onsen UI team and we know that some of our users are already creating apps using Vue and Onsen UI. We are happy to announce that we are currently working on adding better support.

Vue 2 was recently released and it looks very good. The API for creating components will stay almost the same as in the previous version, which makes migration very easy, but internally a lot of changes has been made to make the library more efficient.

Previously we released a small library to make it easier to develop apps with Onsen UI and Vue 1. Since we believe that Vue 2 will gradually replace v1, we are currently focusing our efforts on creating a library for Vue 2 instead.

Vue 2 vs. Vue 1

As mentioned earlier the API has not changed much from v1 to v2. Creating a component in the latest version is very similar to how it is done in v1 but the names of some of the life-cycle callbacks have changed.

Also, Vue 2 is using virtual DOM to speed up rendering and re-rerendering the view. In the diagrams below we can see how the Vue 2 lifecycle is different.

Vue 1 and 2 lifecyle

As we can see some callbacks have been removed and a few have been added.

The beforeCompile and compiled attributes don’t exist in the new version so components that were using those need to be rewritten. Another thing worth to mention is that the $compile function has also been removed so there is no way to manually compile the DOM.

Also, there are two new callbacks that deal with Virtual DOM updates: beforeUpdate and updated.

For people who are familiar with React, the callbacks in v2 should be easy to understand. The naming convention is different which makes the callback names shorter than the React equivalents.

In general, I believe that migrating to v2 is a very simple task.

Vue and Web Components

Onsen UI is created using the Custom Elements v1 API. It’s a simple technology that is used for creating reusable UI components and extend the HTML vocabulary with new tag names.

Since our goal is for Onsen UI to be usable with any frontend library or framework, we need to be careful that we implement all our components in a way that makes them robust and that they can handle being rendered in several different ways since the rendering engine is slightly different for all frameworks.

Vue works very well with Web Components, especially components that are rendered at the leaves of the tree such as buttons, input elements. Basically all components that don’t contain any content of their own.

For components such as the which provides stack navigation and dialogs we need to implement some bindings to make them easy to work with in Vue while all other components should be usable as is.

The following Vue template uses the tag to render Material Design input elements, the value can be bound to a variable without writing any binding code:

<p>
    <ons-input :value="name" @input="onNameChange" modifier="material" placeholder="Name" float></ons-input>
</p>
<p>
    <ons-input type="number" min="0" :value="age" @input="onAgeChange" modifier="material" placeholder="Name" float></ons-input>
</p>
<p>
    Your name is {{ name || 'unknown' }} and you are {{ age }} years old.
</p>

When we run the code we get the following result:

See the Pen Vue 2 and Onsen UI 2 by Andreas Argelius (@argelius) on CodePen.

We are currently working on making all the Onsen UI components robust so they can be rendered correctly by Vue. The next step will be to write a binding library that integrates well with navigation components such as , , and our dialog components.

We need your help!

We are just getting started developing bindings for Vue 2. If you have any requests for how the two libraries should be integrated and what APIs should be available to the developer, let’s discuss in our Gitter channel. We are also looking for people who are experienced Vue developers that would like to contribute to the project with their expertise.

The development will take place in our GitHub repo. Feel free to contribute code and ideas.

Source:: https://onsen.io/

Freebie: 5 Fantastic Bootstrap Footers

By Danny Markov

5-freebie-fantastic-footers

Last time we shared with you a collection of 5 Free Bootstrap 3 Headers that can be used to kick-start any new project. Today we’ve got for you more awesome freebies and this time they are 5 ready-to-use footers templates. Just like all of our freebies, these footer designs are fully responsive, easy to implement, and 100% free to use.

The Footers

All of the footers are created using the Bootstrap 3 library. They are responsive and should look nice on any device and resolution. Each example has its own CSS file, making it very easy to customize and use. The CSS is self-contained and won’t be breaking the styles for the rest of your page.

Footer With Button

How to use

To use any of the templates from the demo, follow these simple steps:

  1. Grab the zip archive from the Download button near the top of the page and extract it.
  2. Open the .html file for the template you want, copy the code inside and paste it in your project.
  3. The styles are located in separate CSS files for each design. You can find them in the /assets/css/ folder. (In the beginning of each file there are styles needed for positioning the demos, you can remove those if you want.)

The only external libraries we’ve used (apart from Bootstrap) are Font Awesome for icons, and on one of the examples an embedded map from Google Maps.

Footer With Map

Footer With Map

If you want to use the Footer With Map template you will need to generate your unique Google API key. To do so, go to the Google API console and grab a Google Maps Embed key. The whole process shouldn’t take more that a couple of minutes.

Free for Commercial Use

You have all rights to customize and use these templates. They are 100% free and can be implemented in both personal and commercial projects, no attribution required (our license page). Enjoy!

Source:: Tutorialzine.com

Tips for using async functions (ES2017)

By Axel Rauschmayer

This blog post gives tips for using async functions. If you are unfamiliar with them, you can read chapter “Async functions” in “Exploring ES2016 and ES2017”.

Know your Promises

The foundation of async functions is Promises. That’s why understanding the latter is crucial for understanding the former. Especially when connecting old code that isn’t based on Promises with async functions, you often have no choice but to use Promises directly.

For example, this is a “promisified” version of XMLHttpRequest:

    function httpGet(url, responseType="") {
        return new Promise(
            function (resolve, reject) {
                const request = new XMLHttpRequest();
                request.onload = function () {
                    if (this.status === 200) {
                        // Success
                        resolve(this.response);
                    } else {
                        // Something went wrong (404 etc.)
                        reject(new Error(this.statusText));
                    }
                };
                request.onerror = function () {
                    reject(new Error(
                        'XMLHttpRequest Error: '+this.statusText));
                };
                request.open('GET', url);
                xhr.responseType = responseType;
                request.send();
            });
    }

The API of XMLHttpRequest is based on callbacks. Promisifying it via an async function would mean that you’d have to fulfill or reject the Promise returned by the function from within callbacks. That’s impossible, because you can only do so via return and throw. And you can’t return the result of a function from within a callback. throw has similar constraints.

Therefore, the common coding style for async functions will be:

  • Use Promises directly to build asynchronous primitives.
  • Use those primitives via async functions.

Further reading: chapter “Promises for asynchronous programming” in “Exploring ES6”.

Async functions are started synchronously, settled asynchronously

This is how async functions are executed:

  1. The result of an async function is always a Promise p. That Promise is created when starting the execution of the async function.
  2. The body is executed. Execution may finish permanently via return or throw. Or it may finish temporarily via await; in which case execution will usually continue later on.
  3. The Promise p is returned.

While executing the body of the async function, return x resolves the Promise p with x, while throw err rejects p with err. The notification of a settlement happens asynchronously. In other words: the callbacks of then() and catch() are always executed after the current code is finished.

The following code demonstrates how that works:

    async function asyncFunc() {
        console.log('asyncFunc()'); // (A)
        return 'abc';
    }
    asyncFunc().
    then(x => console.log(`Resolved: ${x}`)); // (B)
    console.log('main'); // (C)
    
    // Output:
    // asyncFunc()
    // main
    // Resolved: abc

You can rely on the following order:

  1. Line (A): the async function is started synchronously. The async function’s Promise is resolved via return.
  2. Line (C): execution continues.
  3. Line (B): Notification of Promise resolution happens asynchronously.

Returned Promises are not wrapped

Resolving a Promise is a standard operation. return uses it to resolve the Promise p of an async function. That means:

  1. Returning a non-Promise value fulfills p with that value.
  2. Returning a Promise means that p now mirrors the state of that Promise.

Therefore, you can return a Promise and that Promise won’t be wrapped in a Promise:

    async function asyncFunc() {
        return Promise.resolve(123);
    }
    asyncFunc()
    .then(x => console.log(x)) // 123

Intriguingly, returning a rejected Promise leads to the result of the async function being rejected (normally, you’d use throw for that):

    async function asyncFunc() {
        return Promise.reject(new Error('Problem!'));
    }
    asyncFunc()
    .catch(err => console.error(err)); // Error: Problem!

That is in line with how Promise resolution works. It enables you to forward both fulfillments and rejections of another asynchronous computation, without an await:

    async function asyncFunc() {
        return anotherAsyncFunc();
    }

The previous code is roughly similar to – but more efficient than – the following code (which unwraps the Promise of anotherAsyncFunc() only to wrap it again):

    async function asyncFunc() {
        return await anotherAsyncFunc();
    }

Don’t forget await

One easy mistake to make in async functions is to forget await when making an asynchronous function call:

    async function asyncFunc() {
        const value = otherAsyncFunc(); // missing `await`!
        ···
    }

In this example, value is set to a Promise, which is usually not what you want in async functions.

await can even make sense if an async function doesn’t return anything. Then its Promise is simply used as a signal for telling the caller that it is finished. For example:

    async function foo() {
        await step1(); // (A)
        ···
    }

The await in line (A) guarantees that step1() is completely finished before the remainder of foo() is executed.

You don’t need await if you “fire and forget”

Sometimes, you only want to trigger an asynchronous computation and are not interested in when it is finished. The following code is an example:

    async function asyncFunc() {
        const writer = openFile('someFile.txt');
        writer.write('hello'); // don't wait
        writer.write('world'); // don't wait
        await writer.close(); // wait for file to close
    }

Here, we don’t care when individual writes are finished, only that they are executed in the right order (which the API would have to guarantee, but that is encouraged by the execution model of async functions – as we have seen).

The await in the last line of asyncFunc() ensures that the function is only fulfilled after the file was successfully closed.

Given that returned Promises are not wrapped, you can also return instead of await writer.close():

    async function asyncFunc() {
        const writer = openFile('someFile.txt');
        writer.write('hello');
        writer.write('world');
        return writer.close();
    }

Both versions have pros and cons, the await version is probably slightly easier to understand.

Parallelism

The following code make two asynchronous function calls, asyncFunc1() and asyncFunc2().

    async function foo() {
        const result1 = await asyncFunc1();
        const result2 = await asyncFunc2();
    }

However, these two function calls are executed sequentially. Executing them in parallel tends to speed things up. You can use Promise.all() to do so:

    async function foo() {
        const [result1, result2] = await Promise.all([
            asyncFunc1(),
            asyncFunc2(),
        ]);
    }

Instead of awaiting two Promises, we are now awaiting a Promise for an Array with two elements.

No await in callbacks

Remember that await only affects the innermost async function that surrounds it and can only be used directly inside async functions. That is a problem if you want to use one of the Array utility functions map(), forEach(), etc., which rely on callbacks.

Array.prototype.map()

Let’s start with the Array method map(). In the following code, we want to download the files pointed to by an Array of URLs and return them in an Array.

    async function downloadContent(urls) {
        return urls.map(url => {
            // Wrong syntax!
            const content = await httpGet(url);
            return content;
        });
    }

This does not work, because await is syntactically illegal inside normal arrow functions. How about using an async arrow function, then?

    async function downloadContent(urls) {
        return urls.map(async (url) => {
            const content = await httpGet(url);
            return content;
        });
    }

There are two issues with this code:

  • The result is now an Array of Promises, not an Array of strings.
  • The work performed by the callbacks isn’t finished once map() is finished, because await only pauses the surrounding arrow function and httpGet() is resolved asynchronously. That means you can’t use await to wait until downloadContent() is finished.

We can fix both issues via Promise.all(), which converts an Array of Promises to a Promise for an Array (with the values fulfilled by the Promises):

    async function downloadContent(urls) {
        const promiseArray = urls.map(async (url) => {
            const content = await httpGet(url);
            return content;
        });
        return await Promise.all(promiseArray);
    }

The callback for map() doesn’t do much with the result of httpGet(), it only forwards it. Therefore, we don’t need an async arrow function here, a normal arrow function will do:

    async function downloadContent(urls) {
        const promiseArray = urls.map(
            url => httpGet(url));
        return await Promise.all(promiseArray);
    }

There is one small improvement that we still can make: This async function is slightly inefficient – it first unwraps the result of Promise.all() via await, before wrapping it again via return. Given that return doesn’t wrap Promises, we can return the result of Promise.all() directly:

    async function downloadContent(urls) {
        const promiseArray = urls.map(
            url => httpGet(url));
        return Promise.all(promiseArray);
    }

Array.prototype.forEach()

Let’s use the Array method forEach() to log the contents of several files pointed to via URLs:

    async function logContent(urls) {
        urls.forEach(url => {
            // Wrong syntax
            const content = await httpGet(url);
            console.log(content);
        });
    }

Again, this code will produce a syntax error, because you can’t use await inside normal arrow functions.

Let’s use an async arrow function:

    async function logContent(urls) {
        urls.forEach(async url => {
            const content = await httpGet(url);
            console.log(content);
        });
        // Not finished here
    }

This does work, but there is one caveat: the Promise returned by httpGet() is resolved asynchronously, which means that the callbacks are not finished when forEach() returns. As a consequence, you can’t await the end of logContent().

If that’s not what you want, you can convert forEach() into a for-of loop:

    async function logContent(urls) {
        for (const url of urls) {
            const content = await httpGet(url);
            console.log(content);
        }
    }

Now everything is finished after the for-of loop. However, the processing steps happen sequentially: httpGet() is only called a second time after the first call is finished. If you want the processing steps to happen in parallel, you must use Promise.all():

    async function logContent(urls) {
        await Promise.all(urls.map(
            async url => {
                const content = await httpGet(url);
                console.log(content);            
            }));
    }

map() is used to create an Array of Promises. We are not interested in the results they fulfill, we only await until all of them are fulfilled. That means that we are completely done at the end of this async function. We could just as well return Promise.all(), but then the result of the function would be an Array whose elements are all undefined.

Immediately Invoked Async Function Expressions

Sometimes, it’d be nice if you could use await at the top level of a module or script. Alas, it’s only available inside async functions. You therefore have several options. You can either create an async function main() and call it immediately afterwards:

    async function main() {
        console.log(await asyncFunction());
    }
    main();

Or you can use an Immediately Invoked Async Function Expression:

    (async function () {
        console.log(await asyncFunction());
    })();

Another option is an Immediately Invoked Async Arrow Function:

    (async () => {
        console.log(await asyncFunction());
    })();

Unit testing with async functions

The following code uses the test-framework mocha to unit-test the asynchronous functions asyncFunc1() and asyncFunc2():

    import assert from 'assert';
    
    // Bug: the following test always succeeds
    test('Testing async code', function () {
        asyncFunc1() // (A)
        .then(result1 => {
            assert.strictEqual(result1, 'a'); // (B)
            return asyncFunc2();
        })
        .then(result2 => {
            assert.strictEqual(result2, 'b'); // (C)
        });
    });

However, this test always succeeds, because mocha doesn’t wait until the assertions in line (B) and line (C) are executed.

You can fix this by returning the result of the Promise chain, because mocha recognizes if a test returns a Promise and then waits until that Promise is settled (unless there is a timeout).

    return asyncFunc1() // (A)

Conveniently, async functions always return Promises, which makes them perfect for this kind of unit test:

    import assert from 'assert';
    test('Testing async code', async function () {
        const result1 = await asyncFunc1();
        assert.strictEqual(result1, 'a');
        const result2 = await asyncFunc2();
        assert.strictEqual(result2, 'b');
    });

There are thus two advantages to using async functions for asynchronous unit tests in mocha: the code is more concise and returning Promises is taken care of, too.

Don’t worry about unhandled rejections

JavaScript engines are becoming increasingly good at warning about rejections that are not handled. For example, the following code would often fail silently in the past, but most modern JavaScript engines now report an unhandled rejection:

    async function foo() {
        throw new Error('Problem!');
    }
    foo();

Source:: 2ality