The code side of life

QuickTip: Future proof your Promises from angular 1.x to angular 2.

Introduction

user

Shlomi Assaf


QuickTip: Future proof your Promises from angular 1.x to angular 2.

Posted by Shlomi Assaf on .
Featured

QuickTip: Future proof your Promises from angular 1.x to angular 2.

Posted by Shlomi Assaf on .

AngularJS (1.x) is a veteran in the world of frameworks. As such it carries a lot of baggage, some of it not in fashion these days.

Angular's $q is a Promise like library that brought promises to life inside the angular eco-system. As order came to life and the Promise spec emerged a lot of frameworks, including AngularJS faced a dilemma, how to future proof the framework while keeping the current API as is.

Angular's $q has come a long way towards the Promise spec, tough not 100% similar.

Here is how to create a promise using $q, the "Promise" spec way:

var promise = new $q( function(resolve, reject) {  
    // resolve() or reject() your promise here.
});

Looks familiar?

var promise = new Promise( function(resolve, reject) {  
    // resolve() or reject() your promise here.
});

To me it looks like a polyfill, so why not?

// Make sure this is the first "run" block in your app.
angular.module('myApp').run(function($q) {  
    window.Promise = $q;
});

From here on, instead of "injecting" $q into your angular recipes (services, controllers, directive, etc...) just do "new Promise(...)"

If, for some reason, you need to use promises before the run block, use a real polyfill. You should note it to your team, and the meanings of it.

Some points:

  • Try to avoid $q as much as possible.
  • Don't $q.defer, build your own wrappers (or use Promise.defer if you must)
  • Try Promise.all and friends.
  • Don't use notification.

And there you have it, you can eliminate direct $q usage completely.
Once you're ready to upgrade, Promise is already there - no extra work.

NOTE: If you're using a 3rd party library that makes use of Promise and expects a Promise like object behavior - use caution. Most angular 1 projects won't have such packages anyway but if you do have, make some tests and validate that it works since the digest cycle will run on every Promise resolve and exception handling in $q is not the same as Promise, making exception handling a bit tricky.

user

Shlomi Assaf