javascript function execute after a variable got value - javascript

Can function be executed after some variable got value (or changed) in JavaScript?
In my example, the variable is hoisted at first which is declared to be a global, then will assign some value to it in getData() function.
I have tried using .delay() method, but i don't know how much time the ajax needs.
briefly describe:
1) Declaring variable
2) calling getData() function, then assign the data to variable
3) calling funcA() function
4) calling funcB() function and pass function doSomething() as a callback in funcA()
5) calling the callback function in funcB()
6) log the data in doSomething()
<script>
var variable;
variable = getData();
funcA();
function funcA() {
funcB(doSomething);
function doSomething(data) {
console.log(data);
}
}
function funcB(callback) {
if (variable !== undefined) {//it is obviously undefined.
callback(variable);
}
}
</script>
//another js file
<script>
function getData() {
//get data by using ajax
//i don't know how much time it needs.
return data;
}
</script>

change your getdata to this:
function getData() {
$.ajax({
url: "some url",
success: function(result){
variable = result;
//do everything that should be done here or call your callback
});
}

Related

Callback not working - Javascript

I have a (asynchronous) function that gets the ID of a logged in user in Chrome. I'm trying to return the value of the ID with a callback but it keeps returning 'undefined'.
Before someone tries to mark this a duplicate, I used the code from here (and tried other places too): How to return value from an asynchronous callback function? But it didn't work:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
callback(userInfo.id);
});
}
getGaia(function(id){
return id;
});
var gaiaId = getGaia();
I get the following error:
'callback' is a not a function
What exactly am I doing wrong / what is the correct code?
That is because you are not providing a callback.
function doSomethingLater(callback) {
setTimeout(callback, 1000);
}
console.log('This is before the callback');
doSomethingLater(function() {
console.log('This is the callback')
});
So when you are calling var gaiaId = getGaia(); you are not passing in a callback function
[Edit] This is what your code would need to look like:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
// This will call the function that you pass in below
//and pass in userInfo.if as a parameter
callback(userInfo.id);
});
}
var gaiaId = getGaia(function (id) {
// id === userInfo.id from above
// Do something with the id that you pass in
});
You can think of functions like variables in JavaScript,
So you can assign a function to a variable like this:
var foo = function () { ... }
This means that you can pass this into functions like normal variables. When you pass the function in as a parameter, you are assigning the function to the name that you specify in the parameters:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
All I have done above is, instead of creating the variable foo I just created the function inline:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
// Becomes:
function hasCallback(callback) {
callback(); // Using the function that you passed in
}
hasCallback(function () { ... });

Pass a function as a parameter that may not exist yet in Javascript

Is it possible to pass a callback function that does not exist yet? My goal is to have a common function that will wait for another callback function to exist, when it does exist, it should execute it. This is what I have so far, but I can't figure out how to pass the function in that doesn't exist as a function yet.
function RunTemplateFunction(callback, userInfo) {
if ($.isFunction(callback)) {
callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(callback)) {
clearInterval(myInterval);
callback(userInfo);
}
}, 200);
}
}
I run the function like this:
RunTemplateFunction(MyFunctionToRun, GetUserInfo());
I get MyFunctionToRun is undefined for obvious reasons, I also tried the workaround of passing the function as a string and then convert the string to a function using eval(). But that throws the same error. I also thought of using the new function(), but that actually creates a new function.
Any help is appreciated. thank you.
If you call RunTemplateFunction by undefined there is no way we can see, is callback is defined or not, as we don't have reference to anything.
If you can modify the declaration to accept object as below, we can achieve what we want
function RunTemplateFunction(options, userInfo) {
if ($.isFunction(options.callback)) {
console.log('called1',userInfo);
options.callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(options.callback)) {
console.log('Called dynamically!!');
clearInterval(myInterval);
options.callback(userInfo);
}
}, 200);
}
}
var options = {}
RunTemplateFunction(options,{user:122});
options.callback = function(){
console.log("I'm called!!");
}
This will print
Called dynamically!!
I'm called!!
EDIT:
We can also call callback function in following way without setInterval, it will look different but options.callback variable is replaced by template.callMe function and its instantaneous also.
function TemplateRunner(userInfo){
this.callMe = function(cb){
this.templateFunction(cb);
}
this.templateFunction = function(callback){
callback(userInfo);
}
}
var template = new TemplateRunner({user:100})
template.callMe(function(user){
console.log('call me1',user);
});
template.callMe(function(user){
console.log('call me2',user);
})
This will print
call me1 {user: 100}
call me2 {user: 100}

call to a function that inside another function in JavaScript

I want to call a function that is in another function.
example for the functions:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
}
I need to call to funcTwo function, when I click on a button which is outside of these two functions
how can i do it?
No, You can't call unless you return that function.
Function2 is private to function1.
you use
function funcOne() {
return {
funcTwo :function() { // i want to call to this function
//do something
}
}
}
EDIT: Structuring code
function funcOne() {
var funcTwo = function() { // private function
//do something
}
return {
funcTwo : funcTwo
}
}
Now you can call it as:
funcOne().funcTwo()
As you have it defined in your example, you can't. funcTwo is scoped inside of funcOne, so it can only be called from inside funcOne. You can assign funcTwo to a variable that is scoped outside of funcOne and that would work:
var funcRef;
function funcOne() {
funcRef = function funcTwo() {
}
}
In this case, funcRef would hold a reference and could be used, but that reference is only set once funcOne has been executed.
Reading some Douglas Crockford may help you understand...
Try recoding as:
function funcOne() {
this.funcTwo = function() {
}
}
I think you'd have to declare an instance of a funcOne object and then call the funcTwo method of that object. I'm a bit busy at the moment so I can't refine this answer at the moment.
It is not possible as the second function will be created just when the first function is called. it is not existent prior to that.
You would have to define it outside the first function like so:
function funcOne() {
}
function funcTwo() { // i want to call to this function
//do something
}
Or you could also call the first function and return the second function like this:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
return functTwo;
}
And then call it like this:
var f = funcOne();
f();

Making variables available outside a function without globals

I'm struggling to get my head around how to pass information around in javascript. Can some kind person show me how to take a variable from within a function and use it in another function but without making the variable global. I think i need to use return but I am stuck and not sure what to google to get something I can learn from.
For example, how can I make the "json" variable available so i can use it in the "MasterView" function. Thank you in advance.
function fetchData() {
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.App.Properties.setString('cachedJson', this.responseText);
var json = JSON.parse(Ti.App.Properties.getString('cachedJson',''));
},
timeout: 5000
});
xhr.open("GET", site_url + "?get_json=postObjects");
xhr.send();
}
function MasterView() {};
There are numerous ways to go around this without using globals.
Also, what do you mean by "without making the variable global"?
You want to avoid polluting the global namespace or you just don't want your variable to be available in all of your functions?
Here's a way of passing the value from one of your functions to another:
function a(){
var hello = "world";
return hello;
}
function b(){
var result = a();
console.log(result);
}
As you can see function a() returns the variable hello with the value "world".
Now if you call function b() it will store a()'s return value in a variable called result and then log it to the console.
Another option is to use parameters (sometimes called as arguments) in your functions:
function a(){
var hello = "world";
b(hello);
}
function b(arg){
console.log(arg);
}
In this case if you will call function a() it will instantly call function b(), passing the variable hello, so b() will log "world".
Of course the latter aproach is not always a good choice, i.e. you simply don't want your first function to call another one. In that case you can do the following:
function a(){
var hello = "world";
return hello;
}
function b(arg){
console.log(arg);
}
Then call function b() as: b(a());
This way you'll pass function a()'s return value as an argument to function b().
Hopefully this cleared up most of your questions. :)
// Simply add this:
var json;
// and continue...
function fetchData() {
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.App.Properties.setString('cachedJson', this.responseText);
json = JSON.parse(Ti.App.Properties.getString('cachedJson',''));
},
timeout: 5000
});
xhr.open("GET", site_url + "?get_json=postObjects");
xhr.send();
}
function MasterView() {
console.log(JSON.stringify(json))
};
With hopes that it might work...Or:
function fetchData() {
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.App.Properties.setString('cachedJson', this.responseText);
json = JSON.parse(Ti.App.Properties.getString('cachedJson',''));
},
timeout: 5000
});
xhr.open("GET", site_url + "?get_json=postObjects");
xhr.send();
}
function MasterView() {
var json;
fetchData();
console.log(JSON.stringify(json))
};
Global variables are useful for a lot of things, however if the only variable you need is json, and you only need it in the function Masterview, call the function fetchData from the function MasterView and make fetchData return json.
W3 schools is a great tool for javascript and html development. Try this link for more on functions, specifically functions with a return value.
http://www.w3schools.com/js/js_functions.asp

Getting Globally declared variable value from 1 function to another function

I have a very common question about javascript
i have a globally declared variable but how can a function with that variable pass the value in the globally declared variable then use it in the second function??
var ID;
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
alert(ID);
}
})
}
function test1() {
$.getJSON("/TestSite?Test=" + ID; )
}
alert(ID);
test();
test1();
Function test alert the ID but when i declare it Globally it was undeclared.
Can someone help me with this??
Thanks
I think you are expecting getJSON to be synchronous, but it is not. If the calls are dependent you should nest them:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
$.getJSON("/TestSite?Test=" + ID; )
})
})
}
test1 is being called before test has completed its getJSON call
Because getJSON is asynchronous, the proper way do perform what you need is to use the returned ID in the callback of getJSON:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
var theId = this["ID"];
alert(theId);
test1(theId);
}
});
}
function test1(id) {
$.getJSON("/TestSite?Test=" + id);
}
test();
Try this first you set you id to Zero
var ID =0;

Categories

Resources