Variable scope Javascript Module Pattern [duplicate] - javascript

This question already has answers here:
Ajax jquery async return value
(3 answers)
Closed 7 years ago.
I have the following code:
Main.User = (function(){
var currentUser = ''
var get_current_user = function get_current_user(){
Main.Mod.do_ajax('home/get_user_pnp_id','GET',function(data){
currentUser = data.username;
},null);
console.log(currentUser); //Doesn't work. It logs empty string.
return currentUser;
}
return {
get_current_user : get_current_user,
}
})();
The 3rd parameter from Main.Mod.do_ajax() is a callback success function from my ajax call. However I cannot set currentUser inside that callback function.
What seems to be the problem?

It's because your callback hasn't been called yet when the assignment is made since the callback is asynchronous. See Ajax jquery async return value and http://node-tricks.com/return-response-ajax-call/

Related

How can i use JSON data out of callback function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 months ago.
Hi I'm trying to get JSON data from a JSON file. I got it on my JS code but i cant use it out of the callback function. I want to use the data anywhere in my code. I want to pass the data to a variable
My code for getting JSON data is :
async function load() {
let url = 'sorular.json';
let obj;
obj = await (await fetch(url)).json();
return obj
}
load().then(res=>{console.log(res)})
in the THEN, simply call a separate function where res is passed as argument.
function processJSON(data){
//run your other functions here
}
load().then(res=>{processJSON(res)})

Getting the returned value from async function in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
async function someFunction() {
try {
var key = await dec.awsDecrypt('dev-frontend')
return key;
} catch(err) {
}
}
//calling the function
const result = someFunction()
Above I have an asynchronous that returns the value key. I'm trying to retrieve that value by assigning the function to a variable result, but when trying I get Promise { <pending> } as a response. Any suggestions?
Your someFunction will return a promise because you put the async keyword before it.
You are going to need to await it as well.
const result = someFunction().then(console.log)
or
const result = someFunction().then((result)=>console.log(result))
or you can run the whole program inside what is called an immediately invoked function. That way you can make your immediately invoked function async as well and use await in there.

function that has an ajax events return undefined when called [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a function called 'getAuthor' and inside there's an ajax events running (refer below)
function getAuthor(id){
$.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
var author = e.name;
console.log(author);
return author;
});
}
try to run from the console, you'll see it returns "undefined" while console.log display the expected response from the ajax call.
Any, ideas help please?
Unless there is a explicit return from a function , it will always return undefined.
In console it is undefined because the function getAuthor is not returning anything. Not to be confused with the return from $.get.
The console.log statement is inside this asynchronous function. To get a return from the function getAuthor try this
function getAuthor(id){
return $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
var author = e.name;
console.log(author);
return author;
});
}

javascript variable scope issue undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
function getData() {
var photo,
comment,
url;
$.getJSON('http://url.info/verify/settings.php', function (data) {
photo = data.photoMSG;
comment = data.commentMSG;
url = data.photoURL
});
console.log(photo); //undefined
console.log(comment); //undefined
console.log(url); //undefined
}
I'm getting undefined in console log for all of them... How to get these 3 vars visible outside of getJOSN block? I know this have been asked x100 times, I tried windiw.varName but still the same thing..
It's not a scope issue, it's an asynchronous issue. Everything inside the getJSON handler is asynchronous -- so the console.log calls will usually happen after the variables get assigned. Use an async callback instead:
$.getJSON('http://url.info/verify/settings.php', function (data) {
photo = data.photoMSG;
comment = data.commentMSG;
url = data.photoURL;
callback(photo, comment, url);
});
function(photo, comment, url) {
console.log(photo); //undefined
console.log(comment); //undefined
console.log(url); //undefined
}
Because $.getJSON is doing an ajax call, but the code after that is called before the callback within the getJSON is called. So the vars are still undefined. A typical "problem" with asynchronous behaviors.

how can i get return value of javascript function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 8 years ago.
my code like this
var key,value;
//……some code……
function checkReg(i,j){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
return(c.status);
});
}
var temp=checkReg(key,value);
alert(temp);
The problem is when I run it in my browser, it always fist alert undefined then alert the return value; seems like that can not get the return value of function checkReg. I was so confused, what should I do?
That's because your ajax call is running asynch from the rest. Your code will already have returned before before the ajax is even triggered.
So the returning doesn't work like that, you should provide a callback to your function instead of trying to return it.
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});
you cannot do that... since ajax is ashynchronus ... by the time the success function is called and return, the alert will be called thus having temp as undefined or empty.. one way to do this is doing the thing you need to inside the success called back of getJSON... or use $.deffered or callinga calback function..
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});

Categories

Resources