Skip to content
This repository was archived by the owner on Mar 17, 2025. It is now read-only.

Commit d6f09ba

Browse files
committed
utils: add makeNodeResolver function.
Many Firebase methods take Node.js style callbacks where the first argument is null do indicate success or contains error information. Angular uses promises to handle asyncronous flow. The original [Q](https://github.com/kriskowal/q) library by kriskowal (upon which had Angular promises are based) had a `makeNodeResolver` function that eased integration of the two different async flows. This utility function replicates that feature. Usage is as follows: ```javascript var defer = $q.defer(); ref.resetPassword( {email:'[email protected]'}, $util.makeNodeResolver(defer) //automatically resolves/rejects promise ); defer.promise.then(...) // use the promise as you normally would ```
1 parent b1de5aa commit d6f09ba

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/utils.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,17 @@
227227
return def.promise;
228228
},
229229

230+
makeNodeResolver:function(deferred){
231+
return function(err,result){
232+
if(err){
233+
deferred.reject(err);
234+
}
235+
else {
236+
deferred.resolve(result);
237+
}
238+
}
239+
},
240+
230241
wait: function(fn, wait) {
231242
var to = $timeout(fn, wait||0);
232243
return function() {

tests/unit/utils.spec.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,4 +181,28 @@ describe('$firebaseUtils', function () {
181181
});
182182
});
183183

184+
describe('#makeNodeResolver', function(){
185+
var deferred, callback;
186+
beforeEach(function(){
187+
deferred = jasmine.createSpyObj('promise',['resolve','reject']);
188+
callback = $utils.makeNodeResolver(deferred);
189+
});
190+
191+
it('should return a function', function(){
192+
expect(callback).toBeA('function');
193+
});
194+
195+
it('should reject the promise if the first argument is truthy', function(){
196+
var error = new Error('blah');
197+
callback(error);
198+
expect(deferred.reject).toHaveBeenCalledWith(error);
199+
});
200+
201+
it('should resolve the promise if the first argument is falsy', function(){
202+
var result = {data:'hello world'};
203+
callback(null,result);
204+
expect(deferred.resolve).toHaveBeenCalledWith(result);
205+
});
206+
});
207+
184208
});

0 commit comments

Comments
 (0)