PageMethods slows the process and working descending - javascript

I have many pagemethods on my page. Each methods are used for fetching data from the database. I have ordered them in the following way. but my problem is the lines outside the success methods but inside the main function are working before the pagemethods complete the process
function check_valid()
{
// some code
Pagemethod1
function suc1()
{
//some code
PageMethod2
function suc2()
{
//some code
Page Method3
function suc3()
{
//some code
}
function err3(){}
}
function err2(){}
}
function err1(){}
return true; //this line is working before the pagemethods complete the process
}

I'm not familiar with "PageMethods" but it sounds like each of these functions is asynchronous as it is receiving data from a remote database. Because JavaScript operates within one single thread, asynchronous processes usually have an option to attach a callback function that fires once the process is complete. This allows javascript to do other things such as return true while its waiting for your slow database call, explaining your observation.
Instead, use a callback pattern with your database API:
editDatabase(args*, function() {
//Stuff to do database call is complete
});
Alternatively, your database API might use an event pattern:
var myDb = new DB();
myDb.edit(args*)
myDb.bind('complete', function() {
//Stuff to do database call is complete
});
Or, your database API might use promises, which you can read about here.
These patterns may take some getting used to if you are moving from a synchronous language, but they are essential to JavaScript. You can also find a good guide to the asynchronous aspects of JavaScript here.

Change your code as follows
function check_valid()
{
// some code
Pagemethod1
function suc1()
{
//some code
PageMethod2
function suc2()
{
//some code
Page Method3
function suc3()
{
//some code
return true;
}
function err3(){}
}
function err2(){}
}
function err1(){}
}
Because PageMethods will work one by one.

Using a javascript class may help. Also callbacks are key for ajax.
function check_valid(){
var fn = this; //assign this to a variable for ease of use
var callbacks = []; //array to store all results
var calls = []; //all ajax calls
this.complete = function(callback){
function check(){
if(callbacks.length==calls.length){
callback(callbacks);
}else{
setTimeout(function(){
fn.check()
},50);
}
}
return fn;
}
this.callServ(params){
calls.push(params);
params.success = function(ret){
callbacks.push({data:ret,status:'success'});
}
params.error = function(ret){
callbacks.push({data:ret,status:'success'});
}
$.ajax(params);
return fn;
}
return this;
}
This should allow you to do multiple calls systematically and then use a single callback to handle them all. I use jquery ajax to make the ajax call easier, and pass its same parameters.
So it would look like this to use:
var checkValid = new check_valid();
checkValid.callServ({url:url,data:data});
checkValid.callServ({url:url,data:data});
checkValid.callServ({url:url,data:data});
checkValid.complete(function(data){
//data is an array of all call serv returns.
});
This may be far from what you currently have, the amount of information does not tell me enough of what exactly is being done. This example may be a little advanced, but it can give the illusion of being synchronous, at least as close as javascript can get.

I have found my own solution. After a long research i have come to the solution. that is pagemethods will be slow only because of their arrangement. We have to decide where to call it and after which we have to call. Since I have reordered them, it gave some fault. Now its working good.

Related

Mixing sync and async javascript/jquery and getting a success function at the end

Wondering what the best solution to this problem is, also this is not my actual code structure or names but the simplest way to illustrate the problem.
I have a function which was purely used to perform an ajax call and load a template with jquery.
function load(template) {
$('#container').load(template, data, function() {
// complete code here
});
}
Focusing on the 3rd param in $.load(), namely a callback function that runs when the request is complete.
Now I have my load() function in another wrapper function:
function processTask(variable) {
load(variable);
}
The problem I have is I need some code to run after the ajax load is complete, however as my app has grown my wrapper function processTask may or may not invoke an ajax load so I can't perform my must needed code inside the complete callback.
Do I change my $.load() to perform synchronous or just manage my code better so that if I am calling a $.load() it puts my needed code in the callback and if not it places it where I need it to be?
I have read about javascript Promises and I'm unsure if they will help in this situation.
EDIT
So my processTask is an object method.
function classObj(name, fn) {
this.name = name;
this.processTask = fn;
this.load = function(template) {
$('#container').load(template, data, function() {
// complete code here
});
}
}
And in context I do this:
var task = new classObj('taskName', function() {
this.load('myFile.php');
// Or another function and not load() based on whats needed in the task.
});
Basically I have an object that I can add custom methods to at will and they can easily be called dynamically, until now they have always loaded a file.
First, change your load function to return the xhr from get (or ajax):
function load(template) {
return $.get('myFile.php', data, function(result) {
$('#container').html(result);
});
}
Then, within your code you can use when then to perform your code after the load completes if applicable:
var xhr;
/* ... */
if(something){
xhr = load(template);
}
/* ... */
if(xhr){
$.when(xhr).then(doSomething);
} else {
doSomething();
}
And in fact, this can be simplified using the fact that a non-deferred object passed to when (including undefined apparently) will execute the then immediately and get rid of the if:
$.when(xhr).then(doSomething);
If xhr is undefined then when will resolve immediately causing then to execute immediately.

Setting timer after an asynchronous call returns

I have an asynchronous Ajax function which runs a command string at the server side and returns the result to the client. It calls a callback to process the result.
function ajaxCall(commandStr,callback){
var url=......//make a url with the command string
jquery.get(url,function(result){
//process the result using callback
callback(result);
});
}
The asynchronous call (ajaxCall) may take a while to be finished but I want it to do the same command after an interval (1000ms).
I want to write a function that is like this:
function ajaxCallRepeated(interval,commandStr,callback)
I tried closures like this:
function ajaxCallRepeated(interval,commandStr,callback){
//This feature uses closures in Javascript. Please read this to know why and how: http://jibbering.com/faq/notes/closures/#clSto
function callLater(param1,param2,param3){
return (function(){
ajaxCall(param2,function(out,err){
if(param3)param3(out,err);
var functRef = callLater(param1,param2,param3);
setTimeout(functRef, interval);
});
});
}
//the first call
var functRef = callLater(interval,commandStr,callback);
setTimeout(functRef, interval);
}
Then I call it like this:
ajaxCallRepeated(2000,"ls",function(result){
alert(result);
});
But it only runs the command 2 times.
How can I write a function that will reschedule itself after it is called as a callback of an asynchronous function?
PS. I want to fire another Ajax call after the previous one is finished. Also, it worth to mention that axashCallRepeated() will be called with various parameters, so several Ajax calls are running in parallel, but for each commandStr, there is only one Ajax call going on, and after the Ajax call returns, another one will be fired after X seconds.
I would not use setTimeout to trigger the second Ajax call ! Because you never know how long it will take and if it's finished !
As far as you tagged your question right and you ARE using jquery you should consider something like this:
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(){
// The AJAX is successfully done, now you trigger your custom event:
$(document).trigger('myAjaxHasCompleted');
},
dataType: dataType
});
$(function(){
//somehwere in your document ready block
$(document).on("myAjaxHasCompleted",function(){
$.ajax({
//execute the second one
});
});
});
So this would ensure that the ajax post is DONE and was successful and now you could execute the second one. I know its not the exact answer to your question but you should consider on using something like this ! Would make it safer I guess :-)
The key to solve this problem is to save a reference to the closure itself and use it when scheduling the next call:
function ajaxCallRepeated(interval,commandStr,callback){
//This feature uses closures in Javascript. Please read this to know why and how: http://jibbering.com/faq/notes/closures/#clSto
function callLater(_interval,_commandString,_callback){
var closure=(function(){
ajaxCall(_commandString,function(out,err){
if(_callback)_callback(out,err);
setTimeout(closure,_interval);
});
});
return closure;
}
//now make a closure for every call to this function
var functRef = callLater(interval,commandString,callback);
//the first call
functRef();
}
It becomes easier to reason about if you separate things up a bit.
For example, the repetition logic doesn't have to know about AJAX or callbacks at all:
function mkRepeater(interval, fn, fnScope, fnArgs) {
var running;
function repeat() {
if (!running) return;
fn.apply(fnScope, fnArgs);
setTimeout(repeat, interval);
}
return {
start: function() { running = true; repeat(); },
stop: function() { running = false; }
};
}
You can use it like this:
var r = mkRepeater(2000, ajaxFunction, this, ["getStuff", callbackFn]);
r.start();
...
r.stop();

How to make an efficient ajax based javascript script

I usually structure my scripts in javascript like this or something similar when the script depends on some ajax or a server response in general. I really don't feel it's the most efficient way to do things, so what would be a better way to do these types of scripts?
function someclass() {
//some internal variables here
this.var1 = null;
this.var2 = null;
...
//some ajax function which gets some critical information for the other functions
this.getAJAX = function() {
self = this;
urls = "someurlhere";
//jquery ajax function
$.ajax({
type: "GET",
url: url,
dataType: 'json',
complete: function (xhr, textStatus) {
//get the response from the server
data = JSON.parse(xhr.responseText);
//call the function which will process the information
self.processAJAX(data);
}
})
this.processAJAX = function(data) {
//set some of the internal variables here
//according to the response from the server
//now that the internal variables are set,
//I can call some other functions which will
//use the data somehow
this.doSomething();
}
this.doSomething = function() {
//do something here
}
}
So I would use the script something like this:
//instantiate the class
foo = new someClass();
//get the information from the server
//and the processAjax function will eventually
//call the doSomething function
foo.getAjax();
So I really don't like this because it's not clear in the use of the script what is happening. I would like to be able to do something like this:
//instantiate the class
foo = new someClass();
//get info from the server
//in this example, the processAJAX function will not call the doSomething
foo.getAjax();
//do something
foo.doSomething();
This however does not work because usually the response from the server takes some time so when the doSomething is called, the necessary information is not there yet, therefore, the function does not do what it is suppose to do.
How to make this work?
I am sure the answer is already somewhere on StackOverflow, however I could not find anything, so I would appreciate both, either an answer or a link to a resource which would explain this, possible on StackOverflow. Any help is appreciated. Thank you.
The standard pattern for this is to accept a callback function to your asynchronous method, which the class takes responsibility for calling when the operation is complete.
function someclass() {
this.getAJAX = function(callback) {
this.afterAJAXCallback = callback;
...
});
this.processAJAX = function(data) {
...
if (this.afterAJAXCallback) this.afterAJAXCallback();
}
}
Then you can use a closure callback in place to structure your code, much in the way you would when using jQuery's $.ajax:
foo = new someClass();
foo.getAjax(function() {
foo.doSomething();
});
Sounds like you want an ajax event listener or a callback. Do some searches for that and you'll find some solutions. A lot of them will be jQuery-based, but it is certainly possible to do it without jQuery if that is a bad fit for your application.
For jQuery, the relevant documentation is at http://api.jquery.com/jQuery.ajax/. It doesn't call it an event listener, but see the part about context and the callback for succes.
Another possibility would be to do your ajax calls synchronously rather than asynchronously. (Again, do some searches and you'll find lots of stuff.) If you go that route, you want to be careful about making sure that the synchronous call doesn't basically hang your app waiting for a response.
If you use XMLHttpRequest() synchronous you can do it the way you prefer.

AJAX workflow: How do I order the execution of these functions?

I'm trying to figure the best way to get my functions executing in the correct order.
I have 3 functions
function 1 - squirts OPTIONs into a SELECT via JSON and marks them as selected
function 2 - squirts OPTIONS into a 2nd SELECT and marks them as selected
function 3 - gets the values from the above SELECTs along with some additional INPUT values, does an AJAX GET resulting in JSON data, which is read and populates a table.
With JQuery Onload, I execute:
function1();
function2();
function3();
I'm finding function3 is executing before the SELECTs have been populated with OPTIONS and hence the table has no results, because the values sent in the GET were blank.
I know this is probably a very simple problem and that there are probably a dozen ways to accomplish this, but basically I need the best way to code this so that function3 only runs if function1 and 2 are complete.
I've come into Javascript via the back door having learnt the basics of JQuery first!
Thanks for your assistance.
Javascript executes synchronously, which means that function3 must wait for function2 to complete, which must wait for function1 to complete before executing.
The exception is when you run code that is asynchronous, like a setTimeout, setInterval or an asynchronous AJAX request.
Any subsequent code that relies on the completion of such asynchronous code needs to be called in such a manner that it doesn't execute until the asynchronous code has completed.
In the case of the setTimeout, you could just place the next function call at the end of the function you're passing to the setTimeout.
In the case of an AJAX call, you can place the next function call in a callback that fires upon a completed request.
If you don't want the execution of the subsequent function to occur every time, you can modify your functions to accept a function argument that gets called at the end of the asynchronous code.
Something like:
function function1( fn ) {
setTimeout(function() {
// your code
// Call the function parameter if it exists
if( fn ) {
fn();
}
}, 200);
}
function function2() {
// some code that must wait for function1
}
onload:
// Call function1 and pass function2 as an argument
function1( function2 );
// ...or call function1 without the argument
function1();
// ...or call function2 independently of function1
function2();
I recommend you use a Promises library. You can hack simple solutions like other answers suggest, but as your application grows, you'll find you are doing more and more of these hacks. Promises are intended to solve these kinds of problems when dealing with asynchronous calls.
The CommonJS project has several Promises proposals which you should check out. Here is a question I asked on SO about Promises a while back with links to other solutions. Learn more about Promises in this Douglas Crockford video. The whole video is good, but skip to just past half way for promises.
I'm using the FuturesJS library currently as it suits my needs. But there are advantages to other implementations as well. It allows you to do sequences very easily:
// Initialize Application
Futures.sequence(function (next) {
// First load the UI description document
loadUI(next); // next() is called inside loadUI
})
.then(function(next) {
// Then load all templates specified in the description
loadTemplates(next); // next() is called inside loadTemplates
})
.then(function(next) {
// Then initialize all templates specified in the description
initTemplates();
});
Even more powerful is when you need to join async events together and do another action when all of the other async events have completed. Here's an example (untested) that will load a bunch of HTML files and then perform an action only once ALL of them have completed loading:
var path = "/templates/",
templates = ["one.html","two.html","three.html"],
promises = [];
$.each(templates, function(i,name) {
promises[i] = Futures.promise();
var $container = $("<div>");
$container.load(path+name, function(response,status,xhr) {
promises[i].fullfill();
}
});
Futures.join(promises, {timeout: 10000}) // Fail if promises not completed in 10 seconds
.when(function(p_arr) {
console.log("All templates loaded");
})
.fail(function(p_arr) {
console.log("Error loading templates");
});
This might be overkill for your application. But if the application is growing in complexity, using promises will help you in the long run.
I hope this helps!
invoke function2 inside of function1 and function3 inside of function2.
It's not clear why f1 and f2 are executing before f3.
Also, are you using the preferred $(document).ready() or some variation of onload?
It might be helpful if you provide a reproducible test case.
fun3() will only run after both are ready. It might run twice. You can fix this with a lock inside fun3() you would need a Singleton to guarantee it works correctly.
var select1ready = false, select2ready = false;
fun1()
{
// do stuff
select1ready = true;
fun3();
}
fun2()
{
// do stuff
select2ready = true;
fun3();
}
fun3()
{
if (select1ready && select2ready)
{
}
}
fun1();
fun2();

Join 2 'threads' in javascript

If I have an ajax call off fetching (with a callback) and then some other code running in the meantime. How can I have a third function that will be called when both of the first 2 are done. I'm sure it is easy with polling (setTimeout and then check some variables) but I'd rather a callback.
Is it possible?
You could just give the same callback to both your AJAX call and your other code running in the meantime, use a variable to track their combined progress, then link them to a callback like below:
// Each time you start a call, increment this by one
var counter = 0;
var callback = function() {
counter--;
if (counter == 0) {
// Execute code you wanted to do once both threads are finished.
}
}
Daniel's solution is the proper one. I took it and added some extra code so you don't have to think too much ;)
function createNotifier() {
var counter = 2;
return function() {
if (--counter == 0) {
// do stuff
}
};
}
var notify = createNotifier();
var later = function() {
var done = false;
// do stuff and set done to true if you're done
if (done) {
notify();
}
};
function doAjaxCall(notify) {
var ajaxCallback = function() {
// Respond to the AJAX callback here
// Notify that the Ajax callback is done
notify();
};
// Here you perform the AJAX call action
}
setInterval(later, 200);
doAjaxCall(notify);
The best approach to this is to take advantage of the fact that functions are first-order objects in JavaScript. Therefore you can assign them to variables and invoke them through the variable, changing the function that the variable refers to as needed.
For example:
function firstCallback() {
// the first thing has happened
// so when the next thing happens, we want to do stuff
callback = secondCallback;
}
function secondCallback() {
// do stuff now both things have happened
}
var callback = firstCallback;
If both your pieces of code now use the variable to call the function:
callback();
then whichever one executes first will call the firstCallback, which changes the variable to point to the secondCallback, and so that will be called by whichever executes second.
However your phrasing of the question implies that this may all be unnecessary, as it sounds like you are making an Ajax request and then continuing processing. As JavaScript interpreters are single-threaded, the Ajax callback will never be executed until the main body of code that made the request has finished executing anyway, even if that is long after the response has been received.
In case that isn't your situation, I've created a working example on my site; view the source to see the code (just before the </body> tag). It makes a request which is delayed by the server for a couple of seconds, then a request which receives an immediate response. The second request's response is handled by one function, and the first request's response is later handled by a different function, as the request that received a response first has changed the callback variable to refer to the second function.
You are talking about a thing called deferred in javascript as #Chris Conway mentioned above. Similarly jQuery also has Deferred since v1.5.
Check these Deferred.when() or deferred.done()
Don't forget to check jQuery doc.
But to give you some idea here is what I am copying from that site.
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
/* a1 and a2 are arguments resolved for the
page1 and page2 ajax requests, respectively */
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
if ( /Whip It/.test(jqXHR.responseText) ) {
alert("First page has 'Whip It' somewhere.");
}
});
//Using deferred.then()
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
Something like this (schematic):
registerThread() {
counter++;
}
unregisterThread() {
if (--counter == 0) fireEvent('some_user_event');
}
eventHandler_for_some_user_event() {
do_stuff();
}
You can do this easily with Google's Closure library, specifically goog.async.Deferred:
// Deferred is a container for an incomplete computation.
var ajaxFinished = goog.async.Deferred();
// ajaxCall is the asynchronous function we're calling.
ajaxCall( //args...,
function() { // callback
// Process the results...
ajaxFinished.callback(); // Signal completion
}
);
// Do other stuff...
// Wait for the callback completion before proceeding
goog.async.when(ajaxFinished, function() {
// Do the rest of the stuff...
});
You can join multiple asynchronous computations using awaitDeferred, chainDeferred, or goog.async.DeferredList.

Categories

Resources