AngularJS – Create and resolve promises in one line

April 3, 2015 by Brian | 3 Comments | Filed in angular

So much of my test code had the same 3 lines in it to create a promise, and immediately resolve it. Ya know, creating stub promises so your tests don’t cross too many boundaries.

Create and resolve() a promise

 var deferred = $q.defer();
  deferred.resolve(‘This is the old way’);
  return deferred.promise;
 

Replace it in one line!

 return $q.when(‘This is the new way’);
 

Same for reject()

 var deferred = $q.defer();
  deferred.reject(‘This is the old way’);
  return deferred.promise;
 

Replace it in one line!

 return $q.reject(‘This is the new way’);
 

Notes

Yes it’s strange that to resolve you use .when(). I think this is just a quirk of AngularJS and will be changed in Angular 2 since ES6 supports similar (called .reject & .resolve) and it would be not smart to continue to do something different.

This is what I do

April 2, 2015 by Brian | No Comments | Filed in work

Lotsa people can write code. I have a ton of respect for those that take the time to make it so incredibly clear it requires no explanation. I prefer descriptive names over comments. No one writes it beautifully the first time, every time. That’s why just “getting it to work” is never good enough. I am a software gardener, and I really enjoy it.

To that end, I thought this example of a recent refactor would be a good example to share. This actually help us fix a bug which turned out to be the fact that the unit tests was passing in a number for expectedLogoutTime, while the actual code was passing in a Date object. (Hence why I changed the variable name to expectedLogoutDate.)

Before

After