$q in angularjs code example
Example 1: $q use in angularjs
function MyService($q) {
return {
getSomething() {
return $q((resolve, reject) => {
if () {
resolve('Success!');
} else {
reject('Oops... something went wrong');
}
});
}
};
}
angular
.module('app')
.service('MyService', MyService);
Example 2: $q use in angularjs
const handleThirdPartyCallback = someArgument => {
let promise = new Promise((resolve, reject) => {
myCallbackLib(someArgument, response => {
resolve(response);
}, reason => {
reject(reason);
});
});
return promise;
};
handleThirdPartyCallback({ user: 101 }).then(data => {
console.log(data);
});
Example 3: $q use in angularjs
it('should simulate promise', inject(function($q, $rootScope) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue;
promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toBeUndefined();
deferred.resolve(123);
expect(resolvedValue).toBeUndefined();
$rootScope.$apply();
expect(resolvedValue).toEqual(123);
}));