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 problem how to properly call/return one function data. I have this function displayTableWithCountryStates which is calling getCountryStates function. The problem is that when i make request $.get i get proper response, but when i try to return this response, console.log(countryStates) inside displayTableWithCountryStates is empty
countryStatesTables = {
displayTableWithCountryStates: function (source, newForm) {
var countryId = 237;
var countryStates = countryStatesTables.getCountryStates(countryId);
console.log(countryStates); // Response is empty
},
getCountryStates: function (countryId) {
if (countryId !== '' || countryId !== 'undefined') {
$.get(balthazar.settings.logistics.getCountryStatesUrl.url + '/' + countryId, function (data) {
console.log(data.data); //Response is ok, data is present
return data.data;
});
}
}
};
Why and how to properly return data in my displayTableWithCountryStates function. If you need any additional informations, please let me know and i will provide. Thank you!
Asynchronous functions need callbacks to handle the data as we don't know exactly when they would return the output. You can also it with promises.
countryStatesTables = {
displayTableWithCountryStates: function (source, newForm) {
var countryId = 237;
var countryStates = this.getCountryStates(countryId, function(data){
console.log(countryStates);
});
},
getCountryStates: function (countryId, callback) {
if (countryId !== '' || countryId !== 'undefined') {
$.get(balthazar.settings.logistics.getCountryStatesUrl.url + '/' + countryId, function (data) {
console.log(data.data); //Response is ok, data is present
callback(data.data);
});
}
}
};
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to return the result of an api call I've made but I keep on getting undefined as the output. here's the code:
function getProjects() {
var message;
gapi.client.dolapoapi.getProject({
'appid': "test4"
}).execute(function(resp) {
if (!resp.code) {
//get the response and convert it to a string
message = JSON.stringify(resp);
//console.log(resp); i get the correct output here
}
//console.log(message); i get the correct output here
});
//console.log(message); it returns undefined.
return message;
}
I'm not sure what might be wrong. but what I'm trying to do is to return what's in the message variable after it's assigned here:
message = JSON.stringify(resp);
Pass a function as a callback and when the async operation is complete call the function with the data as parameter.
function getProjects(callback) {
var message;
gapi.client.dolapoapi.getProject({
'appid': "test4"
}).execute(function(resp) {
if (!resp.code) {
//get the response and convert it to a string
message = JSON.stringify(resp);
//console.log(resp); i get the correct output here
}
if(callback && typeof callback == "function") {
callback(message);
}
});
}
getProjects(function(message) {
//using a callback to get the data
console.log(message);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this code (The problem is that i can't get a returned value from result file):
function resultit(id) {
var res;
$.ajax({
url: "result",
type: 'POST',
data: "id=" + id,
success: function (result) {
res = result;
if (result == 0) {
alert('warning', 'FAILED !');
} else {
alert('danger', 'SUCCESS !');
}
}
});
return res;
}
alert(resultit(id)); // always undefined
Can you suggest any modification to get the returned value please ? thank you in advance.
The problem is that your res variable is assigned a value in an asynchronous callback (the ajax success function). The affect of this is that your return res; statement is executed before res is assigned a value.
To get a clearer picture of what's happening try this
function resultit(id) {
var res;
$.ajax({
url: "result",
type: 'POST',
data: "id=" + id,
success: function (result) {
res = result;
alert('And this will happen third: ' + res); // ADD THIS LINE
if (result == 0) {
alert('warning', 'FAILED !');
} else {
alert('danger', 'SUCCESS !');
}
}
});
alert('This will happen second'); // AND THIS LINE
return res;
}
alert('This will happen first: ' + resultit(id)); // AND CHANGE THIS LINE
These 3 alerts will show you the order in which the statements are executing.
There a many solutions to this problem, all of them are outlined in the accepted answer to the question posted by #Andreas above.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I created a simple example of my problem
The function count should count the numbers of items that I receive back from a query. However the way I am currently implementing it I lose reference to my function when I call from the route. In this case the function doWork is from another node module that I cannot modify.
Is there anyway to get around this
function Counter(){
this.array = createArray();
};
Counter.prototype.count = function (q){
query(q, function(data){
if(data === "tabe")
{
this.array[0].total++;
}
else
if(data === "chair")
{
this.array[1].total++;
}
else
if(data === "lamp")
{
this.array[2].total++;
}
});
};
createArray = function (){
var array = [];
array.push({item : "table",
total: 0});
array.push({item : "chair",
total: 0});
array.push({item : "lamp",
total: 0});
return array;
};
//The query function is actually in another node module that I cannot edit
query = function( data, callback){
callback(data);
}
module.exports = Counter;
index.js file
/* Process query */
router.get('/submit', function(req, res, next) {
var counter = new Counter();
counter.count("table");
counter.count("table");
counter.count("lamp");
for(var i = 0; i < counter.array.length; i++){
console.log(counter.array[i]);
}
res.end();
});
It is because the execution context of the callback method is not referring to the Counter instance, you can use the Function.bind() to pass a custom context to the callback method.
Counter.prototype.count = function (q) {
query(q, function (data) {
if (data === "tabe") {
this.array[0].total++;
} else if (data === "chair") {
this.array[1].total++;
} else if (data === "lamp") {
this.array[2].total++;
}
}.bind(this));
};
Another option is to use a closure variable
Counter.prototype.count = function (q) {
var self = this;
query(q, function (data) {
if (data === "tabe") {
self.array[0].total++;
} else if (data === "chair") {
self.array[1].total++;
} else if (data === "lamp") {
self.array[2].total++;
}
});
};
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I was having an obsolete JS library which was making API call Synchronous for which I decided to write JS function which can make them Async using jQuery.
In the following code the getData function is to be a generic function which makes API calls according to params passed and then extract data from the received XML/JS.
The second call(getAllData2) needs values from the result set of getData so I need a callback kind of thing in which the subsequent call can be made after the data is available from the 1st call.
Can this be achieved without the ajax success call back as I want getData function to remain generic.
I had tried jQuery promises but that gives me the raw data of the call instead of the processed one which I will have to process in each of the done callback separtely.
getData(param1,param2..){
var retData = {};
......Param dependent code here..
jQuery.ajax({
url:....,
.......
success: function(resp){
if(resp.length > 0){
jQuery.each(resp,function(key,val){
var i = 0;
var retObj = {};
jQuery.each(val,function(k,v){
retObj[k] = v;
i++;
});
retData[key] = retObj;
});
}
---Process recieved XML/JS and Insert values in retData here--
}
});
return retData;
}
var getAllData = getData(x,y);
var getAllData2 = getData(a,b); // this call needs param from getAllData.
Please suggest.
Thanks
Promises are indeed what you should be using.
That will allow you to structure your logic like this:
function processResult(resp) {
var retData = {};
if(resp.length > 0){
jQuery.each(resp,function(key,val){
var retObj = {};
jQuery.each(val,function(k,v){
retObj[k] = v;
});
retData[key] = retObj;
});
}
return retData;
}
getData(x, y)
.then(function (result) {
var processed = processResult(result);
return getData(processed);
})
.then(function (result) { // result is the result of the second getData()
// use result
});
If you want to do pre-processing of the results in your getData() function, again you can do this with promises:
function getData(param1,param2..) {
......Param dependent code here..
return $.ajax({
url:....,
.......
})
.then(function (resp) {
var retData = {};
if(resp.length > 0){
$.each(resp,function(key,val){
var retObj = {};
$.each(val,function(k,v){
retObj[k] = v;
});
retData[key] = retObj;
});
}
return retData;
});
}
getData(x, y)
.then(function (processedResult) {
return getData(processedResult, otherParameter);
})
.then(function (processedResult2) {
// use processedResult2
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm using jQuery. I have a function that fetches data from a remote server called "get_cats". I call it to fill an array with the values returned. When AJAX is completed I want to return the values.
But It doesn't work, the value returned is undefined. This is pretty basic but I can't see where It fails. Does anyone has a clue ?
$(function () {
var url = "http://someurl.com/service/";
var cats = [];
cats = get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
return categories;
});
}
$(document).ajaxStop(function () {
console.log(cats); // fails and returns undefined :'(
});
});
Oh no AJAX is asynchronous, you cannot return anything from it. You should consume the results of an AJAX request only inside the success callback:
$(function () {
var url = "http://someurl.com/service/";
get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
// Only here you can consume the results of the AJAX request
// Do not attempt to return them, it doesn't make any sense
console.log(categories);
});
}
});
You can try:
$.ajaxSetup({async:false});
before AJAX call.
But it will stop browser while respone will be returned.