This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a function and a variable....
var imageURLs = retrieveRemoteImages(vinUrls)
if imageURLs !== undefined) {
// do something
}
function retrieveRemoteImages(urls) {
var imageURls = [];
processSpinnerActivity(START_IMAGES_IMPORT);
importImagesforSlideShow(REMOTE_IMAGES_URL, urls, function (images) {
if (images !== undefined) {
imageURls = images;
return imageURls;
}
})
return imageURls;
}
This does as intended ....
function importImagesforSlideShow(imagePath, urls, call_back) {
var functionName = 'importImagesforSlideShow'
$.ajax({
type: "POST",
url: LOCAL_PROCESSING_MODULE,
data: {data: [imagePath, urls, IMAGE_EXTENSION_QUALIFIER], functionid: functionName},
dataType:"json",
success: function (res) {
processSpinnerActivity(IMPORT_IMAGES_SUCCESS);
call_back(res);
},
error: function (err) {
processSpinnerActivity(IMPORT_IMAGES_ERROR);
console.log(err.message);
}
});
}
The callback works fine, but I am not able to pass the eventual value to imageURLs and I need to, as the next step cannot occur until it has a value.
Any ideas?
Thanks!
This is not a duplicate question, I have no issues with my AJAX returning the async value*
It's not possible like that, you are executing a piece of async code. So your code keeps running while their isn't any data yet. You have to process your data in a callback, for example like this:
function retrieveRemoteImages(urls, callback) {
processSpinnerActivity(START_IMAGES_IMPORT);
importImagesforSlideShow(REMOTE_IMAGES_URL, urls, callback);
}
retrieveRemoteImages(vinUrls, function(imageURLS) {
//do your stuff
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
There is this small function that should logically returns always, but I am getting undefined :-
function hasAccess() {
var dataObj = {
"id" : $scope.groupId
};
$http.post('http://vlinux:9099/GetItems', dataObj).then(
function(response) {
var result = response.data.result;
if(result.includes($scope.screenId)) {
return "ok";
} else {
return "nok";
}
});
}
I started getting downvotes, so wuickly adding, I debugged it and saw http call is bringing expected response and flow is jumping to the right if/else block. Problem is when I am calling this function in a variable its storing undefined.
The call is simple too :-
var allow = hasAccess();
$http.post is not synchronous, but asynchronous.
Thus, all that you have after $http.post is a promise, not the boolean you are expecting.
The documentation show wells how to provide a "callback" to your function, in case of success as well as failure :
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
// for example : manageWHenOk
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// for example : manageWHenKO
});
Your function return a result only if the request is fine. If there is an error your function do nothing! I suggest you to add a catch function.
function hasAccess() {
var dataObj = {
"id" : $scope.groupId
};
$http.post('http://vlinux:9099/GetItems', dataObj).then(
function(response) {
var result = response.data.result;
if(result.includes($scope.screenId)) {
return "ok";
} else {
return "nok";
}
}).catch(function (error) {
// do something
});
}
If you still have undefined it means that your template is loaded before to obtain the response. In order to resolve that you can do the request in the resolve method of the $stateProvider.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
im trying to get data from an ajax function to my actual app but i cant seem to pass the data outside of the function, ive read other questions and tried their recommendation but it doesnt seem to be working because its not waiting for ajax to finish loading before trying to return the data,
im trying to return uid so that i can do something like
user = getUserID('test');
instead of
getUserID('user', function(id){ console.log(id); });
because i am assigning the returned data to a variable
getUserID = function(user, cb) {
var uid;
$.ajax({
type: "GET",
url: "/user_comment.php",
data: {
user: user
},
success: function(result) {
if (result) {
uid = /name="recipient_id" value="(.*)"/g.exec(result)[1];
console.log('1 ' + uid);
if(cb) {
try {
cb(null, uid);
} catch(e) { cb(e); }
}
} else {
console.log("ERROR!! - No data returned !")
}
}
});
console.log('2 ' + uid);
return uid;
},
all it does right now is
2 undefined
1 5511194
2 undefined
1 1462473
2 undefined
1 5469682
so it is not setting the variable
Your code is returning the value of "uid" before any value is applied to it. You can see that your variable is set in "success" callback. This means that this callback will be called only after the asynchronous call is done. Your "getUserID" function will end AND the "return" statement will be executed BEFORE the callback. Play with your code in the debugger, you'll see what's actually going on. So what you should do is use the returned value in the "success" callback instead of the returned value from "getUserID". Like this:
getUserID('test', function(uid){
... do your stuff here => uid is defined and has the value you're looking for
});
But just don't try to do something like:
var uid = getUserID('test');
... things and stuff
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
How do I make a function to continue only after another function which was called by it finished. Something like this :
function FunctionOne() {
//Do something ...
FunctionTwo()
//Rest of the code after two is finished
}
function FunctionTwo() {
//Some code
}
EDIT:
The exact functions are like this :
function FunctionOne() {
//Do something ...
var result;
for (var i = 0 , i < 100 , ++i){
result = FunctionTwo()
}
//Rest of the code after two is finished
console.dir(result); //this here gives me undefined
}
function FunctionTwo() {
$.get("url", function(data)
{
result = data;
console.dir(result); //this gives me the data but the first function is still running and it finishes faster then the data is retured
return result;
}
You have to use jQuery.ajax and set async: false
a simple example:
result = '';
function FunctionTwo() {
jQuery.ajax({
url: 'url',
success: function(data) {
result = data;
console.dir(result);
},
async: false
});
alert(result);
}
This should already do as you request. Unless you specify FunctioTwo to run asynchronously it will block for you.
Edit in response to your edit:
If you want the Ajax call to block then there is no reason to have it as an async call, if you do wish it to remain async then utilize the callback of the ajax call to execute you data handling function instead of placing that code inside the main block.
function FunctionOne() {
//Do something ...
var result;
for (var i = 0 , i < 100 , ++i){
result = AJAXCall(i)
}
}
function HandleAJAXResponse(response,id)
{
console.dir(response)
}
function AJAXCall(id) {
$.get("url",function(data,id){
HandleAJAXResponse(data,id);
});
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have this code
function(config) {
items=[];
Ext.Ajax.request({
url : 'url',
success : function(resp) {
items = [a,b]
}
});
console.log(items);
return items;
},
I want the items array to be available in main function but its coming empty.
Even though this has been answered countless of times, I'll show you a quick example on what you need to do. In short, you can't access data recieved by an ajax call outside of the success handler. You'll need a callback:
function ajaxStuff(config, cb) {
Ext.Ajax.request({
url : 'url',
success : cb
});
}
var config = {};
ajaxStuff(config, function(resp){
//handle the ajax response here
});
http://jsfiddle.net/Yrd7r/
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am facing a quite Strange problem, I dont seem to be able to override variable jSonData from inside the success function of $.get()
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
if(typeof data !== 'object') {
if(settings.debug) console.log('Getting configuration settings from: ', data);
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here
}, 'json');
}
console.log(jSonData); // Gives the same value as it was before
};
Note: The success event of the $.get() is triggered
By the time you logged the value, the $.get() has not overridden jSonData yet since the AJAX request has not returned by that time. Do the console.log inside the function instead.
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here - You just did!
console.log(jSonData);
}, 'json');
I was having that problem because AJAX calls are asynchronous and thus the call would not have been completed when console.log() was executed.
Solution I used to fix my issue was by using deferring methods.
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
var getData = function() {
if(typeof data !== 'object') {
return $.get(data, 'json');
}
else { return jSonData; }
};
getData().done(function(result) {
jSonData = result;
console.log(jSonData); // Gives the same value as it was before
}).fail(function() {
//
});
};