So I have an api request inside of a function thats placed in my Service script.. I have defined the variable "curruser" outside of the function so I can keep its value, however after exiting the follow Scirpt, curruser is empty??
services.js
function fbUserInfo() {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
So the console.log would return the proper JSON object I retrieved from facebook.. but when I return it in the return statement
return {
userInfo: function() {
fbUserInfo();
console.log(curruser);
return curruser;
}
it returns that curruser is an empty object! I did write
var curruser;
into the first line inside the ".factory"
you have to use then() since fbUserInfo() is async function
return {
userInfo: function() {
$.when(fbUserInfo())..then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
}).then(function(){
console.log(curruser);
return curruser;
})
}
Haven't tested this but might work.
var curruser;
function fbUserInfo( callback ) {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
callback(curruser);
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
return {
userInfo: function( callback ) {
fbUserInfo( function(data){
console.log(data);
callback(data);
});
}
Related
Recently started thinking that it was time to do a massive update to my logical operations, and part of that is the proper chaining of Angular JS asynchronous promise calls. Given the following code, how would I re-write it to be a proper chaining of two separate methods? (Yes, I've seen other posts about this, but they all deal with other versions of Angular, or other syntaxes, and I'm looking for something more up-to-date.)
vm.functionName = (
function() {
vm.processing = true;
api.promise1({ Id: vm.Id })
.then(
function(result) {
if (result.error) {
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(result.error));
} else {
api.promise2({ param: vm.param })
.then(
function(result2) {
if (result2.error) {
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(result2.error));
} else {
vm.data = result2.data;
notificationService.success("<h5>Operation successful!.</h5>");
}
vm.processing = false;
}
)
.catch(
function (err) {
console.error(err);
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(err.statusText));
vm.processing = false;
}
);
}
}
)
.catch(
function (err) {
console.error(err);
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(err.statusText));
vm.processing = false;
}
);
}
);
Logically, my brain tells me that I should be able to do something like this:
vm.functionName = (
function() {
vm.processing = true;
vm.promise1()
.then(
vm.promise2()
.then(
notificationService.success("<h5>Operation successful!.</h5>");
vm.processing = false;
);
);
);
}
);
vm.promise1 = (
function() {
api.promise1({ Id: vm.Id })
.then(
function(result) {
if (result.error) {
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(result.error));
}
}
)
.catch(
function (err) {
console.error(err);
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(err.statusText));
}
);
}
);
vm.promise2 = (
function() {
api.promise2({ param: vm.param })
.then(
function(result) {
if (result.error) {
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(result.error));
} else {
vm.data = result2.data;
}
}
)
.catch(
function (err) {
console.error(err);
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(err.statusText));
}
);
}
);
Update:
the "api...." calls above call to my service.js layer, where methods exist like such:
promise1: function (params, error) {
return $http
.post("/C#Controller/Method1", params)
.then(handleSuccess)
.catch(function (e) {
handleError(e, error);
});
},
promise2: function (params, error) {
return $http
.post("/C#Controller/Method2", params)
.then(handleSuccess)
.catch(function (e) {
handleError(e, error);
});
},
Updated, per Pop-A-Stash's ideas, as now implemented:
//#region Api Calls and Helper
function apiCallOne() {
return api.promise1({ Id: vm.Id });
}
function apiCallTwo() {
return api.promise2({param: vm.param });
}
function handleApiCallError(resultOrError, ngModelToSet) {
var errMsg = resultOrError.statusText === undefined ? resultOrError.error === undefined ? "Unknown Error" : resultOrError.error : resultOrError.statusText;
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(errMsg));
//This allows updating things like variables and ng-model goodies, via an inset function.
if (ngModelToSet) {
ngModelToSet();
}
}
//#endregion
//#region Initialization
function init() {
vm.pgLoaded = false;
apiCallOne()
.then(
function(result) {
if (!result.error) {
vm.data = result.data;
vm.pgLoaded = true;
} else {
handleApiCallError(result, function() { vm.pgLoaded = true; });
}
}
)
.catch(function(errorOne) { handleApiCallError(errorOne, function() { vm.pgLoaded = true; }); });
}
init();
//#endregion
You could shorten your code significantly using recursion to call the next promise in an array of objects containing promises and their parameters using something similar to this:
function runPromises(promises) {
var first = promises.shift();
first.function(first.params).then(function(resp) {
if (promises.length > 1) {
runPromises(promises);
}
}).catch(function (error) {
handleError(error);
});
}
with an initial array of something like this:
var promises = [
{
function: promise1,
params: any
},
{
function: promise2,
params: any
}
];
If each promise response requires individual handling you could add a callback to be fired after the promise is resolved for each promise.
If you want to chain them in a specific order, then you are already doing it correctly. However I see some code duplication that could be cleaned up:
vm.apiCallOne = apiCallOne;
vm.apiCallTwo = apiCallTwo;
vm.runChainedCalls = runChainedCalls;
function runChainedCalls() {
vm.processing = true;
vm.apiCallOne()
.then(function(result1) {
if(!result1.error) {
vm.apiCallTwo().then(function(result2) {
if(!result2.error) {
notificationService.success("<h5>Operation successful!.</h5>");
vm.data = result2.data;
vm.processing = false;
}
else {
handleError(result2);
}
})
.catch(function(errorTwo) {
handleError(errorTwo)
});
}
else {
handleError(result1);
}
})
.catch(function(errorOne) {
handleError(errorOne);
});
}
function apiCallOne(){
return api.callOne(param); //don't forget to return the promise object
};
function apiCallTwo() {
return api.callTwo(param); //don't forget to return the promise object
};
function handleError(resultOrError) {
notificationService.danger("<h5>An error occurred.</h5><h6>Details: {0}</h6>".format(resultOrError.statusText));
vm.processing = false;
}
You only need one .then() and .catch() for each call in your controller. Anymore than that is code duplication.
If you want to run them concurrently and don't care about order, you would use the $q.all() function to run them at the same time:
function runConcurrentCalls() {
$q.all([api.callOne(param), api.callTwo(param)]).then(function(responseArray) {
// responseArray contains array of both call responses
console.log(responseArray[0]);
console.log(responseArray[1]);
})
.catch(function() {
//something went wrong with one or both calls
});
}
I'm a beginner with AngularsJs and I've got a question about the controller structure.
This is my employeeController.js
(function()
{
angular.module('employeeApp').controller('employeeController', employeeController);
function employeeController(employeeFactory,$routeParams,departmentFactory,schoolFactory,mentorFactory,constants,$location,$scope) {
var vm = this;
vm.employee = null;
vm.employees = null;
vm.profilePicture = null;
vm.mentors = null;
vm.schools = null;
vm.departments = null;
vm.roleId = constants.roleid;
vm.internEducators = null;
vm.overviewMentors = function() {
mentorFactory.overview(constants.companyid).then(function(response)
{
vm.mentors = response;
});
}
vm.create = function()
{
employeeFactory.create(vm.employee,vm.profilePicture).success(function(response,status)
{
if(status == 200)
{
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewInternEducators = function() {
employeeFactory.overviewInternEducators(constants.companyid).then(function(response)
{
vm.internEducators = response;
});
}
vm.overviewSchools = function() {
schoolFactory.overview(constants.companyid).then(function(response)
{
if(angular.isDefined(response[0].SchoolId))
{
vm.schools = response;
}
else
{
console.log('leeg!');
}
});
}
vm.overviewDepartments = function() {
console.log('test');
departmentFactory.overview(constants.companyid).then(function(response)
{
vm.departments = response;
});
}
vm.show = function() {
vm.isAdmin = employeeFactory.isAdmin();
employeeFactory.show($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.showDeleted = function() {
employeeFactory.showDeleted($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.update = function()
{
employeeFactory.update(vm.employee, vm.profilePicture).success(function(response, status)
{
if(status == 200)
{
vm.show(); // Zodat de nieuwe afbeelding wordt weergegeven
$.toaster({ message: 'De werknemer is geupdated' });
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewDeleted = function() {
employeeFactory.overviewDeleted().then(function(response)
{
if(angular.isDefined(response[0].EmployeeId))
{
vm.employees = response;
}
});
}
vm.delete = function() {
employeeFactory.delete($routeParams.id).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is verwijderd' });
$location.path('/home');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.permanentDelete = function(employeeId) {
employeeFactory.permanentDelete(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is permanent verwijderd' });
$location.path('/prullenbak/werknemers');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.restore = function(employeeId) {
employeeFactory.restore(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is teruggezet' });
$location.path('/werknemer/' + employeeId);
}
else
{
if(angular.isArray(response))
{
angular.forEach(response, function(error)
{
$.toaster({ priority : 'danger', message : error[0]});
});
}
}
});
}
<!--ng-init-->
vm.editEmployee = function()
{
vm.show();
vm.overviewDepartments();
vm.overviewInternEducators();
vm.overviewMentors();
vm.overviewSchools();
}
vm.createEmployee = function() {
vm.overviewMentors();
vm.overviewSchools();
vm.overviewDepartments();
vm.overviewInternEducators();
}
<!--redirects-->
vm.editRedirect = function(werknemerId)
{
$location.path('/werknemer/edit/' + werknemerId);
}
vm.showTrashedEmployeeRedirect = function(werknemerId)
{
$location.path('/prullenbak/werknemer/' + werknemerId);
}
}
})()
As you can see I use 2 methods called editEmployee and createEmployee (at the end). I use these 2 with the create employee page and the edit employee page. On both pages there are a couple of comboboxes that have to be loaded. In for example my create employee page I say ng-init="employeeController.createEmployee()" and then those comboboxes are filled.
I know this is not the best approach so how could I do this on a different and better way?
There are several ways to structure you app but the style guide endorsed by the Angular team is maintained by John Papa.
Refer to Angular Style Guide by John Papa.
Based on that:
First I would suggest that you split the create, show, edit and delete functionality into separate controllers. This helps with ensuring each controller does only one single thing.This is in line with the idea of Single Responsibility and Separation of Concerns
Secondly since it seems you are using the controllerAs syntax you wouldn't need to inject scope into your controller.
Here is the code for creating an employee(sth like create-employee.controller.js
(function () {
'use strict';
angular.module('employeeApp').controller('CreateEmployeeController', CreateEmployeeController);
//ngInject is used to help create minify safe version of the file during the build process.
//You should have this somewhere in your build process
/** #ngInject **/
function CreateEmployeeController(constants, departmentFactory, employeeFactory, $location, mentorFactory, schoolFactory) {
var vm = this;
vm.create = create;
getMentors();
getSchools();
getDepartments();
getInternEducators();
function getMentors() {
return mentorFactory.overview(constants.companyid).then(function (response) {
vm.mentors = response;
});
}
function getSchools() {
return schoolFactory.overview(constants.companyid).then(function (response) {
if (angular.isDefined(response[0].SchoolId)) {
vm.schools = response;
}
else {
console.log('leeg!');
}
});
}
function getDepartments() {
return departmentFactory.overview(constants.companyid).then(function (response) {
vm.departments = response;
});
}
function getInternEducators() {
return employeeFactory.overviewInternEducators(constants.companyid).then(function (response) {
vm.internEducators = response;
});
}
}
function create() {
return employeeFactory.create(vm.employee, vm.profilePicture).success(function (response, status) {
if (status == 200) {
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function (response) {
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function (error) {
if (i <= 2) {
$.toaster({priority: 'danger', message: error});
}
i++;
});
});
}
})();
You would then create the other controllers by splitting the functionality following this example.
I have a Web API 2 register method as follows :-
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
and an angular Controller that posts to this api as follows :-
angular.module('monfusportsstoreApp')
.controller("registerCtrl", function($scope, UserService) {
var vm = this;
vm.register = register;
vm.Error = '';
function register() {
UserService.createUser(vm.user)
.then(function (response) {
console.log(response.data);
console.log(response.status);
if (response.success) {
console.log('Registration successful');
$location.path('/registerSuccess');
} else {
errorMessages = parseErrors(response);
for (var i = 0; i < errorMessages.length; i++) {
vm.Error += errorMessages[i];
}
}
});
}
function parseErrors(response) {
var errors = [];
for (var key in response.ModelState) {
for (var i = 0; i < response.ModelState[key].length; i++) {
errors.push(response.ModelState[key][i]);
}
}
return errors;
}
})
and the UserService is as follows :-
angular.module("monfusportsstoreApp")
.factory("UserService", function($http, ENDPOINT_URI){
var url = ENDPOINT_URI + '/api/Account/';
var errorMessage = [];
return {
getAllUsers: function() {
return $http.get(url).then(handleSuccess, handleError('Error getting all users'));
},
createUser: function(user) {
return $http.post(url + "/Register", user)
.then(handleSuccess, handleError);
}
}
function handleSuccess(res) {
return res.data;
}
function handleError(res) {
return res.data;
}
});
Now I am managing to trap the response error correctly and displaying the message, however when the Register API is successful and sends the OK, the response is always empty, and as so this piece of code
if (response.success) {
console.log('Registration successful');
$location.path('/registerSuccess');
is never triggered.
How can I trap the status 200 OK so that I can redirect the user to the RegisterSuccess page?
Thanks for your help and time!
I have solved this question.
In the UserService, I needed to return
function handleSuccess(res) {
return res.status;
}
so that in the controller, I can capture the response status
function register() {
UserService.createUser(vm.user)
.then(function (response) {
if (response == 200) {
console.log('Registration successful');
$location.path('/registerSuccess');
} else {
errorMessages = parseErrors(response);
for (var i = 0; i < errorMessages.length; i++) {
vm.Error += errorMessages[i];
}
}
});
}
I am brand new to AngularJS and I'm debugging someone else's code. I am getting the following error when I debug in Google Chrome:
TypeError: accountService.logIn(...).success is not a function.
Here is some of my code. The problem is in the signUp form on the line accountService.logIn(signupform).success(function (response) {. If more info is needed please let me know.
Here is my entire controller.
(function () {
'use strict';
angular
.module('vidaexpress')
.controller('accountController', accountController);
accountController.$inject = ['$rootScope', '$state', '$stateParams', 'accountService', 'facebookService', 'toastr'];
function accountController($rootScope, $state, $stateParams, accountService, facebookService, toastr) {
var vm = this;
vm.logIn = logIn;
vm.signUp = signUp;
vm.signOut = signOut;
vm.facebookLogin = facebookLogin;
vm.facebookLogout = facebookLogout;
vm.recoveryPassword = recoveryPassword;
vm.resetPassword = resetPassword;
vm.sendVerifyEmail = sendVerifyEmail;
function logIn(loginform) {
vm.signinloading = true;
accountService.logIn(loginform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.setUserInfo(response);
if (!$rootScope.returncust) {
window.sessionStorage.setItem('returncust', true);
}
vm.isAccountOpen = false;
}
}, function (error) {
toastr.error(error.error);
}).finally(function () {
vm.signinloading = false;
});
}
function signUp(signupform) {
vm.signuploading = true;
accountService.signUp(signupform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.logIn(signupform).success(function (response) {
accountService.setUserInfo(response);
logIn();
}).error(function(error) {
toastr.error(error.error);
});
}
},function (error) {
toastr.error('System Error');
}).finally(function () {
vm.signuploading = false;
});
}
function signOut() {
//Log out API
//accountService.logOut();
//Log out Facebook
var userInfo = accountService.getUserInfo();
if (userInfo.facebookLogin) {
facebookLogout();
}
//Log out UI
accountService.setUserInfo(null);
vm.isAccountOpen = false;
$state.go('main.index');
}
function facebookLogin() {
facebookService.login();
}
function facebookLogout() {
facebookService.logout();
}
function recoveryPassword(email) {
accountService.recoveryPassword(email).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('An email has been sent.');
}
}, function () {
toastr.error('System Error');
});
}
function resetPassword(model) {
model.customerId = $stateParams.id;
model.token = $stateParams.token;
accountService.resetPassword(model).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Your password has been reset.');
}
}, function () {
toastr.error('System Error');
});
}
function sendVerifyEmail() {
accountService.sendVerifyEmail().then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Email has sent');
}
}, function () {
toastr.error('System Error');
});
}
}
})();
Here is my account.server.js file.
(function () {
'use strict';
angular
.module('vidaexpress')
.service('accountService', accountService);
accountService.$inject = ['$http', '$window', '$rootScope', 'apiUrl'];
function accountService($http, $window, $rootScope, apiUrl) {
var baseUrl = apiUrl.account;
var cookieUser;
var sessionName = 'userInfo';
this.logIn = logIn;
this.logOut = logout;
this.signUp = signUp;
this.setUserInfo = setUserInfo;
this.getUserInfo = getUserInfo;
this.confirm = confirm;
this.recoveryPassword = recoveryPassword;
this.resetPassword = resetPassword;
this.sendVerifyEmail = sendVerifyEmail;
function logIn(credential) {
return $http({
method: 'POST',
url: baseUrl + 'token',
headers:{ 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
grant_type: 'password',
email: credential.email,
password: credential.password
}
}).then(function (response) {
if (!response) {
return { error: 'System Error' };
} else if (response.error) {
return { error: response.error };
} else {
return response.data;
}
}, function (error) {
return { error: 'System Error' };
});
}
function logout() {
return $http.post(baseUrl + 'logout');
}
function signUp(userInfo) {
return $http.post(baseUrl + 'signup', userInfo);
}
function setUserInfo(userInfo) {
cookieUser = userInfo;
$rootScope.currentUser = userInfo;
$window.sessionStorage.setItem(sessionName, JSON.stringify(userInfo));
}
function getUserInfo() {
if (!cookieUser) {
cookieUser = JSON.parse($window.sessionStorage.getItem(sessionName));
}
return cookieUser;
}
function confirm(customerId, token) {
$http.get(baseUrl + 'verifyEmail?id=' + customerId + '&token=' + token);
}
function recoveryPassword(email) {
return $http.get(baseUrl + 'recoveryPassword?email=' + email).then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
function resetPassword(model) {
return $http.post(baseUrl + 'resetPassword', model).then(function () {
return null;
}, function(){
return { error: 'System Error' };
});
}
function sendVerifyEmail() {
return $http.get(baseUrl + 'sendVerifyEmail').then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
}
})();
The way your return pattern is working in the service requires your controller to use .then() rather than success()
accountService.logIn(loginform)
.then(function (response) {
I am trying to figure out how to use Promises with the AMS Javascript API.
These are the two functions I have created that will be 'Promised'
function checkUsername(username, table) {
return table.where({username: username}).read({
success: function (results) {
if (results.length === 0) {
return true;
} else {
return false;
}
},
error: function(error) {
return false;
}
});
}
function checkEmail(email, table) {
return table.where({email: email}).read({
success: function (results) {
if (results.length === 0) {
return true;
} else {
return false;
}
},
error: function(error) {
return false;
}
});
}
checkUsername(body.username, accountsTable).then(function (results) {
if (results) {
return checkEmail(body.email, accountsTable);
} else {
response.send(400, {message: 'This username is already in use.'});
}
}).then(function(results) {
if (results) {
response.send(200, {message: 'Can proceed with sign up.'});
} else {
response.send(400, {message: 'This email address is already in use.'});
}
});
I am trying to use the promises as I would in Parse, but it's clearly not working. The console logs keep spitting out an Internal Server Error and that .then() is not a function of the object. I'm assuming I am missing a require or something in order to have the Promises functionality?
Error in script '/api/register.js'. TypeError: Cannot call method 'done' of undefined
at exports.post (D:\home\site\wwwroot\App_Data\config\scripts\api\register.js:30:59)
[external code]
I have realized what I was doing wrong.
I have now decided to use the Q Node Module for my promises.
var q = require('q');
exports.post = function(request, response) {
// Use "request.service" to access features of your mobile service, e.g.:
// var push = request.service.push;
var tables = request.service.tables;
var accountsTable = tables.getTable('Accounts');
var params = request.body;
checkUsername(params.username, accountsTable).then(function (result) {
if (result.length === 0) {
return checkEmail(params.email, accountsTable);
} else {
response.send(400, {message: 'This username is in use.'});
}
}).then(function (results) {
if (results.length === 0) {
return;
} else {
response.send(400, {message: 'This email address is already registered.'});
}
}).then(function () {
response.send(200, {message: 'Username and email are unique. You can register!'});
});
};
function checkUsername(username, table) {
var deferred = q.defer();
table.where({username: username}).read({
success: function (result) {
deferred.resolve(result);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
function checkEmail(email, table) {
var deferred = q.defer();
table.where({email: email}).read({
success: function (result) {
deferred.resolve(result);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}