I have a function that takes a callback as a parameter, this function has a child function inside of it that I need to actually execute the passed callback that was passed to the parent when it's (the child function) done.
Example:
function Update(callback){
var db = Ti.Database.open('xxxxx'); //Open local database
var data = Ti.Network.createHTTPClient(); //Open a URL to obtain data to put into db.
data.onload = function(){
//loop through JSON file obtained from HTTPClient and place data into the DB.
callback(); //I need THIS to trigger the parents callback to tell the next function that Update() is done.
}
data.open("GET","URL");
data.send();
}
I'm pretty unexperienced when it comes to callbacks, so maybe I'm over thinking this one. Any help would be appreciated! Thanks all!
EDIT: Fixed - This code above works as expected. Somehow, because this Update function was being called while the DB was being created (another function creates the DB, then that callback function calls this Update function), it was still updating the DB, but wasn't calling the callback inside onload. I called the callback to trigger Update later, and it now works as expected. There were never any errors in the Appcelerator Console, so I'm not exactly sure how or why the DB was updated without the callback being called, but it was.
Related
The below code gets a state from latitude/longitude coordinates. How can I extract the value "result.body.region" from the scope of the anonymous function and use it in a higher scope?
latitude=tweets[0].latitude
longitude=tweets[0].longitude
var Request = unirest.get("https://montanaflynn-geocoder.p.mashape.com/reverse?latitude="+myobj.latitude+"&longitude="+myobj.longitude)
.header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxx")
.header("Accept", "application/json")
.end(function (result) {
state = result.body.region
});
What I want to do is write a callback function that will wait for the asynch request to finish and use that information in a different scope. I am self taught on javascript so I am struggling to understand callbacks. How can I do this?
The code you have already will do that.
You are probably trying to read the value of state before the callback has fired.
This is why we normally put the code to process the data in the callback: to make sure it runs after the asynchronous event has occurred.
I have a problem with QlikView in the browser: I have a listbox and try to access it using an initialize script.
The script is registered by using the InitWorkbench function, using its BodyOnLoadFunctionNames parameter. So far, this works, and the initializer is run at startup.
Inside the initializer I try to do the following:
var doc = Qv.GetCurrentDocument();
var listbox = doc.GetObject('LB01');
Afterwards, when I have a look at listbox.Type, unfortunately it is undefined. If I delay execution of this query, it correctly says LB, hence apparently the query works - but only when it is executed delayed.
So, obviuosly there's a timing problem, and it seems as if the initializer runs too early (or I am doing something wrong).
Can anybody point out what the solution is (or give me a hint on what I am doing wrong)?
Okay, I've found the solution: The internal update function did not run yet, and all the values are only available once this function ran, so you need to provide a callback to the call to GetObject (that gets called after the update function):
var doc = Qv.GetCurrentDocument();
var listbox = doc.GetObject('LB01', function () {
console.log(listbox.Type); // => 'LB'
});
I've a javascript method defined as follows:
updtCrtEdtPage = function() {PrimeFaces.ab({source:'j_id_ev',formId:'j_id_es',process:'typeNewLOB_in lobIdForEdit j_id_ev',update:'createLOBFullPagePanel',oncomplete:function(xhr,status,args){prepareForCrtEdtFullPage();},params:arguments[0]});}
I want to execute certain method (afterComplete()) whenever this method has finished executing. (This method actually initiates an ajax request & appends the received HTML data on the DOM). So I want my afterComplete() method to be executed whenever ajax response has been received.
I cannot directly do like:
updtCrtEdtPage();
afterComplete();
as this would call the afterComplete() soon after ajax request is initiated & not completely finished executing yet.
Is there any JS/ jQuery way I could do that ?
You could pass afterComplete as a parameter so your function can call it when the ajax call is complete. Something like this...
updtCrtEdtPage = function(callback) {
PrimeFaces.ab({
source:'j_id_ev',
formId:'j_id_es',
process:'typeNewLOB_in lobIdForEdit j_id_ev',
update:'createLOBFullPagePanel',
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
callback();
},
params:arguments[0]
});
}
updtCrtEdtPage(afterComplete);
Since you say you can't modify updtCrtEdtPage, but you can modify prepareForCrtEdtFullPage I'd suggest using a global variable to determine which callback function to call when the method is complete...
updtCrtEdtPageCallback = afterComplete;
and then in prepareForCrtEdtFullPage just add the last line...
updtCrtEdtPageCallback();
The first method is tidier, but the second will suffice for your particular situation.
your updtCrtEdtPage = function() has an oncomplete callback which is called when the ajax response has been received, add your afterComplete function in that callback and it will execute after the ajax request has been completed.
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
afterComplete()
}
Imagine this scenario:
I have a link that fires up a JavaScript function(has an Ajax request in it).
The JavaScript function has a parameter passed by the link's onclick='jsFunction(param)'.
The JavaScript function sends the parameter value in a function inside a controller that sets the param value to a session variable.
The function in the controller will then send the new value of the session variable back to the JavaScript function's Ajax request.
When the data reached into the Ajax request, another function will be called using the data being passed.
Question:
Since I am talking about the session variable's value being passed to an Ajax request, how can I process the data came from the link to the second function in real-time? I want to post the code here but it's too verbose with the info I only need.
The current state of my code is that, I can't fetch the right/latest data. Instead, I get the previous data came from the previous link I clicked.
Is there an Ajax feature that I can only proceed to the next function if the first function is done processing the latest data?
Any help will be much appreciated.
You can use the callback to any of the jQuery AJAX methods to delay execution of another function until after the request is complete.
$.post('/some/url', somedata, function(returnData) {
// put the code you want to execute on completion here
});
or If you have already defined your function to be called after returning data, you can just write like this:
$.post('/some/url', somedata, processData);
I have a function which makes an AJAX request to a server and returns relevant information after it completes.
I have another function which manipulates some variables in its namespace based on the returned information.
Currently, I am appending a 'callback' argument to the first function, which is called when the request completes. This, however, blurs the purpose of the first function - instead of being a 'getInfo' function, it's become a 'getInfoAndDo' function.
Ideally, I'd like to call the second function (a 'do' function, which calls the first function, a 'get' function) and does its thing.
I have looked around and found jQuery methods such as .ajaxStop and .ajaxComplete, but they seem to only to work when bound to DOM elements. Is there any way to do this entirely in javascript?
e.g.
function _getEventAttendance(uid, callback) {
var attendQuery = FB.Data.query('SELECT eid,rsvp_status,start_time FROM event_member WHERE uid = {0}', uid);
FB.Data.waitOn( [attendQuery],
function (args){
callback(args[0]);
}
);
}
function logAttendance(attendance){
console.log(attendance);
}
Currently, I am doing:
_getEventAttendance(123456789, logAttendance);
which seems ridiculous to me.
Is there a way to write the code such that I can change the code snippet inside _getEventAttendance / remove the callback argument:
FB.Data.waitOn( [attendQuery],
function (args){
return args[0];
}
);
and then make calls that are equivalently as simple as :
logAttendance.ajaxComplete(_getEventAttendance(123456789));
(I'm just making up the syntax for this, I have no idea how it's supposed to be written.)
$.when(<AJAX Request>).then(function(response){...});
Optionally use $.pipe() to filter response first.