AWS Javascript SDK Function return - javascript

Hello how can I write the following code so that there is no race condition if I return inside the get() function it only returns from that function but if I return from the outer function it prematurely returns.
function checkifvalid (userIdPassed) {
// code to be executed
var params43 = {
TableName: 'users',
Key: {
'pid': req.user.iden
}
}
var returnVal = null
docClient.get(params43, function (err43, data43) {
if (err43) {
return res.json({'errasdsd342sd': 'erhf32623hrf'})
} else {
if (data43.Item.useract && data43.Item.curadmin != '0') {
returnVal = true
} else {
returnVal = false
}
}})
if (returnVal !== null) {
return returnVal
}
}

Related

array mapping not returning value react

I have the following function
churnModel = () => {
if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
return("N/A")
} else {
this.props.churnModel.map((churn) => {
if (churn === undefined || churn.length === 0) {
return("N/A")
} else {
return(churn.map((model) => {
this.service(model.scoreModelId)
}))
}
})
}
};
The this.service functions looks like this...
service(e) {
switch(e.toString().toLowerCase()) {
case "in":
return <span>in</span>
case "rpt_callr":
return <span>repeat</span>
default:
return <span>na</span>
}
}
I am expecting to display the result in here:
<div className="riskScore">{this.churnModel()}</div>
Nothing gets displayed, but when I put in logs, those get printed.
What is happening here?
you need to put return before this.props.churnModel.map.this.service(model.scoreModelId)
A function will return undefined if nothing is nothing is returned.
map() takes a callback and changes each element of array to return value of the that callback. If you don't return anything all elements will be undefined
You can also get rid of return before this.service(model.scoreModelId) by removing {}.Like this.
return(churn.map((model) => this.service(model.scoreModelId)))
Here is the code
churnModel = () => {
if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
return("N/A")
} else {
return this.props.churnModel.map((churn) => {
if (churn === undefined || churn.length === 0) {
return("N/A")
} else {
return(churn.map((model) => {
return this.service(model.scoreModelId)
}))
}
})
}
};
You have to use return statement in couple of lines:
churnModel = () => {
if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
return("N/A")
} else {
return this.props.churnModel.map((churn) => {
if (churn === undefined || churn.length === 0) {
return("N/A")
} else {
return(churn.map((model) => {
return this.service(model.scoreModelId)
}))
}
})
}
};
Why do you need return? It's because you're using curly braces.

angular factory store promise result

I have a factory object that contain private object, which is used to cache result retrieved from the api using the factory available functions.
global.mainApp.factory('SessionFactory', function (UserEndpointsResource, SiteEndpointsResource) {
var data = {
/**
* #type {boolean|null}
*/
isLoggedIn: null
};
return {
isUserLoggedIn: function (callback) {
if (data.isLoggedIn != null) {
callback(data.isLoggedIn);
}
else {
UserEndpointsResource.isLoggedIn().$promise.then(function (res) {
var isUserLoggedIn = res.status == 1;
// Trying to set the result to the outer scope data variable
data.isLoggedIn = isUserLoggedIn;
callback(isUserLoggedIn);
}, function (failureData) {
data.isLoggedIn = false;
callback(false);
});
}
},
...
};
});
The problem that every time I call the isUserLoggedIn function, data.isLoggedIn is always null.
How can I alter the factory data object inside the promise then function?
Thanks.
Using the suggestion supplied in the comments, aka do not store promise results, store promises themselves, this is the modified working code!
global.mainApp.factory('SessionFactory', function (UserEndpointsResource, SiteEndpointsResource) {
var data = {
/**
* #type {boolean|null}
*/
isLoggedIn: null
};
return {
isUserLoggedIn: function (callback) {
if (data.isLoggedIn != null) {
data.isLoggedIn.then(function (isLoggedIn) {
callback(isLoggedIn.status == 1);
});
}
else {
data.isLoggedIn = UserEndpointsResource.isLoggedIn().$promise.then(function (res) {
var isUserLoggedIn = res.status == 1;
callback(isUserLoggedIn);
return isUserLoggedIn;
}, function (failureData) {
data.isLoggedIn = false;
callback(false);
return null;
});
}
}
};
});

Callback return empty array js

Here is the function with in sql queries call.
I need return callback only after all queries done.
But it return an empty array
How to return array with data after all?
`
function getUserSales(days, callback){
getUserByLastLoginDay(days, function (users) {
var userArray = [];
_.each(users, function (user) {
getMostFavoredCat(user.id, function (cat) {
if(!cat || cat.length == 0){
return false;
} else {
user.mostFavoredCat = takeMostRepeatingObj(cat);
}
getRelatedSaleByCat(user.id, user.mostFavoredCat.id, function (sales) {
user.sales = sales;
userArray.push(user)
})
})
})
callback(userArray);
})
}
`
callback function first parameter is always an error
callback(null,userArray)
you can make use of async.js for the better control flow
npm i async --save
const async = require('async');
function getUserSales(days, callback){
getUserByLastLoginDay(days, function (users) {
var userArray = [];
async.each(users, function (user, cb) {
getMostFavoredCat(user.id, function (cat) {
if(!cat || cat.length == 0){
return false;
} else {
user.mostFavoredCat = takeMostRepeatingObj(cat);
}
getRelatedSaleByCat(user.id, user.mostFavoredCat.id, function (sales) {
user.sales = sales;
userArray.push(user)
cb();
})
})
}, (err) => {
if (err) {
return callback(err);
} else {
callback(null, userArray);
}
})
})
}
I think it will Works:
function getUserSales(days, callback){
getUserByLastLoginDay(days, function (users) {
var userArray = [];
_.each(users, function (user) {
getMostFavoredCat(user.id, function (cat) {
if(!cat || cat.length == 0){
return false;
} else {
user.mostFavoredCat = takeMostRepeatingObj(cat);
}
getRelatedSaleByCat(user.id, user.mostFavoredCat.id, function (sales) {
user.sales = sales;
userArray.push(user)
})
})
callback(userArray);
})
})
}

Problems understanding the AngularJS promise API - AuthenticationService

Good evening everybody. I startet creating a mobile application with AngularJS,Ionic & Cordova some weeks ago. I try to create a AuthenticationService for this app using a given API.
I checked some tutorials and created this and it seems to work besides the promise handling. I have got a deficit there.
Maybe someone good help me :)
Here i handle the access to certain pages/states.
$rootScope.$on('$stateChangeStart', function (event, next, nextParams, fromState) {
if ('data' in next && 'authorizedRoles' in next.data) {
var authorizedRoles = next.data.authorizedRoles;
if (!AuthService.isAuthorized(authorizedRoles)) {
event.preventDefault();
$state.go($state.current, {}, {
reload: true
});
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
}
}
if (next.name == 'app.admin' || next.name == 'app.bonus') {
AuthService.isAuthenticated().then(function (response) {
}, function (response) {
var alertPopup = $ionicPopup.alert({
title: 'Error1!',
template: 'Sorry, You have to login again.'
});
event.preventDefault();
$state.go('app.login');
$log.log(response + '1er');
});
}
});
Here I perform the user-login
.controller('LoginCtrl', function ($scope, $ionicPopup, AuthService, $state, $log, $q) {
$scope.data = {};
$scope.login = function (data) {
$q.all([
AuthService.login(data.username, data.password),
AuthService.isAuthenticated()
]).then(function (data) {
console.log(data[0]);
console.log(data[1]);
if (data[0] == false) {
var alertPopup = $ionicPopup.alert({
title: 'Error!',
template: 'Sorry, You have to login again.'
});
}
if (data[1] == true) {
$state.go('app.bonus', {}, {
reload: true
});
} else {
var alertPopup = $ionicPopup.alert({
title: 'Error!',
template: 'Sorry, You have to login again.'
});
}
});
};
})
Here I created the service handling the user-role, validation & creation of the cookie - Every API-call needs a nonce which is created also
.service('AuthService', function ($q, $http, USER_ROLES, $log) {
var link = 'http://example/api/';
var username = '';
var isAuthenticated = false;
var role = '';
var mycookie = '';
var mynonce = '';
function checkCookie() {
mycookie = window.localStorage.getItem('LOCAL_COOKIE');
$log.info(mycookie);
if (mycookie) {
$http.get(link + 'get_nonce/?controller=user&method=generate_auth_cookie&insecure=cool').then(
function (result) {
if (result.data.status == "ok") {
mynonce = result.data.nonce;
$log.info(mynonce);
} else {
return false;
}
},
function (err) {
return false;
});
$http.get(link + 'user/validate_auth_cookie/?cookie=' + mycookie + '&nonce=' + mynonce + '&insecure=cool').then(
function (result) {
if (result.data.status == "ok") {
return true;
} else {
window.localStorage.removeItem('LOCAL_COOKIE');
return false;
}
},
function (err) {
return false;
});
} else {
return false;
}
}
function doLogin(name, pw) {
var loginAttempt = false;
$http.get(link + 'get_nonce/?controller=user&method=generate_auth_cookie&insecure=cool').then(
function (result) {
if (result.data.status == "ok") {
mynonce = result.data.nonce;
$log.info(mynonce);
} else {
loginAttempt = false;
}
},
function (err) {
loginAttempt = false;
$log.info(err);
});
mycookie = $http.get(link + 'user/generate_auth_cookie/?username=' + encodeURIComponent(name) + '&password=' + encodeURIComponent(pw) + '&nonce=' + mynonce + '&insecure=cool').then(
function (result) {
if (result.data.status == "ok") {
mycookie = result.data.cookie;
loginAttempt = true;
username = name;
if (username == 'MarkusK') {
role = USER_ROLES.admin
} else {
role = USER_ROLES.public
}
window.localStorage.setItem('LOCAL_COOKIE', mycookie);
$log.info(mycookie);
} else {
loginAttempt = false;
}
},
function (err) {
loginAttempt = false;
$log.info(err);
});
$log.info('test1' + loginAttempt);
return loginAttempt;
};
var login = function (name, pw) {
return $q(function (resolve, reject) {
if (doLogin(name, pw)) {
resolve('Login success.');
} else {
reject('Login Failed.');
}
});
};
var validCookie = function () {
return $q(function (resolve, reject) {
if (checkCookie()) {
resolve('Cookie success.');
} else {
reject('Cookie Failed.');
}
});
};
var logout = function () {
mycookie = undefined;
username = '';
isAuthenticated = false;
window.localStorage.removeItem('LOCAL_COOKIE');
};
var isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (checkCookie() && authorizedRoles.indexOf(role) !== -1);
};
return {
login: login,
logout: logout,
isAuthorized: isAuthorized,
isAuthenticated: validCookie,
username: function () {
return username;
},
role: function () {
return role;
}
};
})
Maybe someone got time to help me and I finally understand the promise API.
Thank you.
You have a nice illustrated definition here:
http://andyshora.com/promises-angularjs-explained-as-cartoon.html.
Let' say we have the following code (isn't meaning anything it's only to explain the promise concept):
var a = 1;
a = foo();
a = a + 2;
Because JavaScript is asynchronous, the second instruction (the call to foo()), won't block the thread.
if foo() is waiting for other ressource (value from a server), it won't wait and will get into the third instruction (a = 2).
The promise is used to tell JavaScript thread: "Hey don't forget to comeback when I'll be ready, you promised me :)".

How to call function?

I have this function:
$scope.PinTicketSearch = function(pinTicket) {
if (pinTicket != null) {
ticketService.searchTicket(pinTicket)
.then(function(response) {
$location.search({
"ticketPin": pinTicket
});
$scope.TicketDetail = response;
$scope.ShowDetailsAboutTicket = true;
});
}
}
and i have this part of code:
if ($location.search().ticketPin)
{
}
How can i call this function $scope.PinTicketSearch and pass parameters from $location.search().ticketPin. I tried with $scope.PinTicketSearch($location.search().ticketPin) but i get an error
PinTicketSearch is not a function
You should to use a callback, instead of your if:
$scope.PinTicketSearch = function(pinTicket, success) {
if(pinTicket != null) {
ticketService.searchTicket(pinTicket)
.then(function(response) {
$location.search({
"ticketPin": pinTicket
});
$scope.TicketDetail = response;
$scope.ShowDetailsAboutTicket = true;
success();
});
}
}
and your "if", will be:
$scope.PinTicketSearch(pinTicket, function() {
// your original "if" body
});

Categories

Resources