In the mentioned sample code I'm trying to get a value for val variable. I declared it with global scope. And add some console log to verify values. But inside of the function it assign value without problem. But out of the function val is undeclared. why is that?
$.validator.addMethod("serialverify", function(){
var val;
$("#serialno").keyup(function(){
serial().done(function(data){
console.log('final = ' + data);
val = data;
console.log(val);
});
}); console.log(val);
return val;
}, "Please enter valid serial code");
There is a fundamental problem in your code. The assignment is taking place in a callback function, which means it'll only execute when the action keyup is made.
However, the statement return val is happening synchronously.
Suggestion -
You can wrap it in a promise of some sort and resolve it when done is executed. Something on the lines of -
......done( function(data) { ..... resolve(val); })
or declare var val; as global that is outside, the addMethod function
Related
I have problem with 'return' means in this code.
1.
function func4() {
var str = "function works.";
console.log(str);
}
func4();
2.
function func4() {
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
Both of them, their result is 'function works.'.
I know that return used for exit function but I'm still confuse when I have to use return exactly.
Sorry about my super basic question :(
As far as I understand 'return' assigns value to a function and returns it, so you're displaying function's value. In the first case you are just simply invoking a function to display a string.
Let's analize this two scenarios:
You have a function that initialize a variable with a predefinided value, and then, you log the value. Then, outside the function you execute it
You have the same variable but with the difference that instead of loggin the value inside the function, you returned it from it. So you can initialize the funcion and store the value on another variable var value = func4();.
Let me try to explain it with some requirements.
I want a function which returns me some data instead of passing a variable and updating the variable in function.
You call a function and it is always best to test negative scenarios first. So in case of negative scenario you can return it from there it self.
In your second case if you see you are getting a value from that function and then printing it. Same thing you can not do using first function.
Always there are workarounds for everything. In the end it depends on your need and what is best suited for that situation.
Both of those functions don't equal the same thing, but they do log the same string.
func4() in #1 is equal to undefined, because it returns nothing.
func4() in #2 returns (gives back) the value "function works.", a string, which is then given to console.log outside of the function.
function func1() {
var str = "function works.";
// console.log(str);
}
func1();
function func2() {
var str = "function works.";
return str;
}
// console.log(func2());
console.log(func1() === undefined);
console.log(func2() === 'function works.');
If you want to use the func4() value for further calculations without calling it again, then you would return {value}.
For e.g
function func4(userInput) {
return userInput % 2 == 0;
}
var response = func4(userInput);
if(response == true) {
console.log('user entered an even number');
} else {
console.log('user entered a odd number');
}
// from here you can use the value of response n times without calling the function again.
Whereas, if you don't return then you will have to call the function x number of times whenever you want to re-user the response of it.
function func4(){
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
//here return means you are returning the value of variable 'str'.
You can find the details here.
https://learn.microsoft.com/en-us/cpp/c-language/return-statement-c?view=vs-2019#:~:text=A%20return%20statement%20ends%20the,value%20to%20the%20calling%20function
I'm new to Node.js and I'm experimenting with it.
Since values from one promise are not available globally I'm trying a way to assign value to a variable that can be accessed anywhere down the chain.
What I found is the first block of code always ends in catch and second block works OK the only difference being assignment of value.
Can someone help me with this in doing it right way.
var test = (req,callBack)=>{
var value;
return querydb.checkstatus(req).then((result)=>{
value = 1;
return(result);
}).then((result)=>{
if(result!=null){
callBack(null, value);
}
}).catch((errorMessage)=>{
callBack({Msg:"From Catch"},null);
})
};
var test = (req,callBack)=>{
var value;
querydb.checkstatus(req).then((result)=>{
return(result);
}).then((result)=>{
if(result!=null){
callBack(null, "from then");
}
}).catch((errorMessage)=>{
callBack({Msg:"From Catch"},null);
})
};
I have a function that I'm calling. Called getStatus(). But this function requires there to be a defined SessionStorage variable that could be present. If the variable is present then I want to go ahead and execute the getJob() function. If it's not present I want to try to define the SessionStorage variable and then execute the getJob() function.
Like this:
function getStatus()
{
if (sessionGet("jwt") != null)
{
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
else
{
var myValue = '{{ myValue }}';
console.log("Token is missing, acquiring another one!");
var nextToken = setTimeout(function(){ getSessionToken(myValue); }, 5000);
console.log("Reissued token issued is");
console.log(nextToken);
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
}
And here is the function that reads the SessionStorage variable:
function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key)
if (stringValue !== null) {
let value = JSON.parse(stringValue)
let expirationDate = new Date(value.expirationDate)
if (expirationDate > new Date()) {
return value.value
} else {
window.sessionStorage.removeItem(key)
}
}
return null
}
When I look at the Chrome console I see the SessionStorage variable being written, but the getJob() function that reads the variable doesn't see it. If I retry then the getJob() function is able to read it. My thought is that the getJob() function is firing before the variable has been written. That's why I tried the setTimeout() in there.
Any suggestions?
As ztadic91 pointed out, I needed to wrap the setTimeout around the getJob() function call, since it needed to wait for the SessionStorage variable to be created. After doing that things tested out fine. Appreciate the quick assist!
I have a controller which initializes my value as such:
$scope.showThing=true;
I toggle the value with ng-click like
ng-click="showThing=!showThing"
which works ok but then if I try using the same value in a function inside the controller it behaves irrational, to say the least.
Something as simple as alerting the value in an interval function only gets the right value the first time it iterates after changing the value, sometimes not even that.
Since it's something so trivial I wouldn't want to create a factory for this alone, so I hope there's someone who can tell me what am I doing wrong here.
Your question is not straightforward, can you post the code. Here is hoisting issue.
var a = 10;
console.log("value of 'a' before hoisting: "+a);
(function(){
console.log("value of 'a' after hoisting: "+a);
var a;
})();
Result:
value of 'a' before hoisting: 10
value of 'a' after hoisting: undefined
This may be, because interval is initiated once, and then only is returning the same value over and over. Try something similar to this, with a getter style function involved:
$scope.showThing=true;
var getShowThing = function() {
return $scope.showThing;
};
$scope.displayTr=function(){
alert(getShowThing());
};
$interval(function() {
//get data from a factory .then(function(response) {
if (response.status === 200) {
$scope.info = response.data;
} else {
console.log('Error occured' + response.status);
}
});
$scope.displayTr();
}, 5000);
Hope this helps.
In my AngularJS application I am doing the following
$http.get('/plugin/' + key + '/js').success(function (data) {
if (data.length > 0) {
console.log(data);
// Here I would also need the value of 'key'
}
});
Now I need to access the key value within the success callback, i.e. I need to know which value it had when the get() request has been made.
Any "best practice" how to do so?
PS: I can do the following, but is there a better way?
var key = config.url.split('/')[2];
Solution 1:
$scope.key = key;
$http.get('/plugin/' + key + '/js').success(function (data) {
if (data.length > 0) {
console.log(data, $scope.key);
}
});
Solution 2 (Updated per Jim Hong's observation in his answer):
$http.get('/plugin/' + key + '/js').success((function(key) {
return function(data) {
console.log(key, data);
}
})(key));
Reference to #geniuscarrier
The working solution on my side is
$http.get('/plugin/' + key + '/js').success((function(key) {
return function(data) {
console.log(key, data);
}
})(key));
Since using #geniuscarrier, I'l get
data undefined error
.
Technically speaking, this is not an AngularJS problem but a feature of javascript
first of all, functions that you defined inside a scope will have access to local variable and parameter of its parent scope
function parent(arg){
var local
function child(){
// have access to arg and local
}
}
Scope actually works well with the parent-child analogy: if you are the parent and you own a cookie, of cause you are welling to share it with your children...but if you are a kid...your cookie is your cookie, your parent is not allowed to touch it :). In other words, inner scope can access outer scope but it does not work both ways
So you should definitely be able to do:
$http.get('/plugin/' + key + '/js').success(function (data) {
if (data.length > 0) {
console.log(data, key); //as long as you can pass it to $http.get as an argument
//you can access it here
}
});
Secondly, because of the event-driven nature of javascript, inner function store references to the outer function’s variables. you probably have heard of this
functions in javascript are objects
local variables and parameters are thus private members of the function:
function ObjectA(){ // define a constructor
var x = 10 // private variable
changeX : function(){
x = 20 // access and MODIFY a variable of parent scope
}
}
if you can understand how private variable works in javascript, then you basically understand what closure is. Thus, for call back function, it is very possible that by the time it is triggered, the value of the parent scope variable is already changed. To fix this, you can use an Immediately Invoked Function Expression (IIFE)
$http.get('/plugin/' + key + '/js').success((function(currentKeyValue) {
return function(data) {
console.log(currentKeyValue, data);
// again, currentKeyValue is a REFERENCE to outer function's
// parameter. However, since String is passed by value in javascript
// currentKeyValue of outer scope is a DIFFERENT string that has the
// same value as KEY when it is invoked
}
})(key)); // immediately invoke the function passing the key as a parameter
Instead of polluting scope or complicating with iif, another cleaner way is to create a callback function and call it with parameters;
var myCallBack = function (key) {
return function (data) {
if (data.length > 0) {
console.log(data, key);
}
}
}
$http.get('/plugin/' + key + '/js').success(myCallBack(key));
Phew, I was looking for this answer for so long, but it's good it is here. Just to update it, since legacy promise methods success and error have been deprecated and we should use the standard then method instead.
Solution 2 in #geniuscarrier and #jim-horng answers may be rewritten like this:
$http.get('/plugin/' + key + '/js').then(
(function(key) {
return function(data) {
console.log(key, data);
}
})(key),
function(data) {
//error handle
});