This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
on my App namespace i've just defined a function:
version 1
window.App = {
isLogged: function () {
$.get('/user/isLogged', function (data) {
if (data == 'true') {
return true;
}
return false;
});
}
};
version 2
window.App = {
isLogged: function () {
var test = $.get('/user/isLogged');
console.log(test.responseText);
}
};
On version 1 when i try the function on firebug 'App.isLogged()' i got a nice undefined :S
On version 2 when i try the function on firebug, the responseText seems to be undefined :stuck:
I'm pretty new about javascript, and maybe a scope issue...
The goal of my function is clear i think, there's a better way to achieve this?
on first version
$.get is asynchronous that's why you don't get a return value
on second version
$.get returns deferred object that doesn't have responseText field
window.App = {
isLogged: function () {
var dfd = $.Deferred();
$.get('/user/isLogged', function (data) {
if (data == 'true') {
return dfd.resolve();
}
return dfd.reject();
});
return dfd.promise();
}
};
$.when(App.isLogged()).then(function() {
//your code
}).fail(function() {
//fail code
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to return an object inside a callback function
In the following situation, the console.log() show the result as expected
var dVizModule = (function(){
let dataset;
function loadData(fileName) {
dataset = d3.csv(fileName, (data) => {
dataset = data;
console.log(dataset);
});
};
return {
loadData: loadData
}
})();
dVizModule.loadData("data/time_scale_data.csv")
but when I try to use return in callback function the story is different and it returns undefined
var dVizModule = (function(){
let dataset;
function loadData(fileName) {
dataset = d3.csv(fileName, (data) => {
dataset = data;
return dataset;
});
// return dataset; or even here!
};
return {
loadData: loadData
}
})();
console.log(dVizModule.loadData("data/time_scale_data.csv"))
Since its a callback based workflow, the code above won't work. d3.csv is an asynchronous function, you can only get the result through a callback passed to it and hence even loadData needs to follow the same pattern.You just need to write something like this.
var dVizModule = (function(){
function loadData(fileName,callback) {
d3.csv(fileName, (data) => {
callback(data);
});
};
return {
loadData: loadData
}
})();
dVizModule.loadData("data/time_scale_data.csv",(data)=>{
console.log(data);
})
This question already has answers here:
Why does JQuery.getJSON() have a success and a done function?
(2 answers)
Closed 5 years ago.
I would like to know if there are any conceptual differences between these two codes:
Code 1:
$(function(){
var url = "url";
$.getJSON(url, function(data){
console.log(data);
})
});
Code 2:
$(function(){
var url = "url";
$.getJSON(url).done(function(data){
console.log(data);
})
});
In which situation the $.getJson().done() method is most relevant ?
The First one uses a callback function as a second param. This allows you to execute code after the function is completed. Note, you are in a separate function.
The Second also uses a callback function as a promise but it is working different under the hood.
// version one
setTimeout(function() {
doStuff1();
doStuff2();
}, 1000)
// version one - callback
function doStuff1() {
doSomething1("value", function(responce) {
console.log(responce);
});
};
function doSomething1(v, cb) {
if (typeof v === "string") {
cb(true);
} else {
cb(false);
}
return false;
}
// note the function will always return false but the callback gets the value you want
// version 2, class with promise callback
// look at the class function and see how it works slightly differently
function doStuff2() {
var $ = new doSomething2();
$.Something("value").done(function(resp) {
console.log(resp)
});
};
class doSomething2 {
constructor() {
this.v = false;
}
Something(val) {
if (typeof val === "string") {
this.v = true;
} else {
this.v = false;
}
return this;
}
done(cb) {
return cb(this.v);
}
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I can't get my head around how to return the value from uniqueCheck() to isValid. I've added in a setTimeout to simulate the async operation.
function isValid(data) {
uniqueCheck(data, function(val) {
return val;
//true
});
// need the value here
}
function uniqueCheck(data, cb) {
// do something with data async
setTimeout(function () {
cb(true)
}, 1000);
}
console.log(isValid("some data"));
To use asynchronous calls in your code you can use Promises or for example if you use jQuery you can make use of Deferred object.
//async function using $.Deferred
function asyncFunction(){
var dd = $.Deferred();
setTimeout(function(data) {
dd.resolve('loaded');
}, 500);
return dd.promise();
}
//somwhere in your code
asyncFunction().then(function(value){
//do stuff when Deferred object is resolved
//value = 'loaded'
})
in your code:
function isValid(data) {
uniqueCheck(data).then(function(){
//value is available here
});
// but not here
//because this code is executed earlier then callback
}
function uniqueCheck(data, cb) {
var dd = $.Deferred();
// do something with data async
setTimeout(function () {
cb(true)
}, 1000);
return dd.promise();
}
you have to return the result through an callback function
function isValid(data, callback) {
uniqueCheck(data, function(val) {
callback(true);
return val;
//true
});
// need the value here
}
function uniqueCheck(data, cb) {
// do something with data async
setTimeout(function () {
cb(true)
}, 1000);
}
//console.log(isValid("some data"));
isValid("some data", function(value){
console.log(value);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have the following function in javascript:
function checkFunc(msg) {
$.getJSON("myurl.php", {
dtccode: msg
}, function(j) {
return j.boolField;
}); //JSON call
}
And I call it in another function:
function check(msg) {
var ret = checkFunc1(); //some other function
ret = checkFunc2() && ret; //some other function
ret = checkFunc3() && ret; //some other function
ret = checkFunc() && ret;
if (ret) {
//code
}
}
My problem is, that I know the checkFunc should return false, but it returns true. I think this may be a synchronization issue, but I don't know what to do.
Can anyone help?
AJAX is asynchronous. Means that you have to use callback function to get the result. Like so:
function checkFunc(msg, callback) {
$.getJSON("myurl.php", {
dtccode: msg
}, function(j) {
callback(j.boolField);
}); //JSON call
}
and
function check(msg) {
checkFunc(msg, function(result){
alert(result);
});
}
EDIT: Using deferred system:
$.getJSON("myurl.php").done(function(j) {
callback(j.boolField);
});
You can also add fail() to check for possible error. Check the docs: http://api.jquery.com/jquery.getjson/
This question already has answers here:
Jquery .each() - return value undefined
(3 answers)
Closed 9 years ago.
Why the does following Javascript function return "undefined" in alert.
here is the snipptet
var tests = validateUserSelectedExperType(userSelectedOptioName);
alert(tests);
Code
function validateUserSelectedExperType(inp) {
$.each(splitter.getFirstPaneContent(), function (index, item) {
var splitterinner = splitter.getFirstPaneContent()[index];
var getLabel = splitterinner.getFirstPaneContent()[0];
if (getLabel.getText() == inp) {
return true;
} else {
return false;
}
});
}
You're returning from the nested function, not from the validateUserSelectedExperType function. Set a boolean and update that value instead. At the end, return it:
function validateUserSelectedExperType(inp) {
var flag = false;
$.each(/* ... */, function (index, item) {
// ...
if (getLabel.getText() == inp) {
flag = true;
return false;
}
});
return flag;
}
That's because your return statements are within $.each() anonymous function. Returning falsefrom that function will stop the each loop.
You have to return something for the main function (I can't understand your code logic, so I can't help you in that).