Spontaneous Publicity
blogs are the new phone book

Asp.Net Ajax: How do you know all of your Ajax calls have completed?

August 22, 2007 07:24 by Luke

Some Background

Here is a situation I ran into recently: I have an Asp.Net Ajax service (.asmx) which has a method used to create rows in a database similiar to:

[WebMethod]
public int CreateItem(string description, double value)

This method basically created a row in the database and returns the id of the item created. It is called from javascript like this:

function MyButtonClicked() {
    MyNamespace.Service.CreateItem("My Item", 5.3, OnSucceeded, OnFailed);
}

function OnSucceeded(result, userContext, methodName) {
}

function OnFailed(error, userContext, methodName) {
}

If you are not familiar with calling Ajax web services from javascript, you can read more from the Calling Web Services from Client Script in ASP.NET AJAX article on asp.net. Basically, I am just calling my CreateItem method (which is part of a .asmx service) from javascript - how this magic happens isn't really too important to understand the problem I was facing.

Notice that the last two parameters I passed into my CreateItem call in javascript are references to callback methods that should be called in the event that my call succeeded or failed. A successful call will end up calling back my OnSucceeded method which has 3 parameters:

  • result - this contains any values returned from my method. In this case it will be the id of the item that was inserted.
  • userContext - this is an optional item that can be passed into the original call to the method and will just be passed on to the callback method. I am not using this parameter in this situation
  • methodName - this is the name of the method that was called which resulted in the OnSucceeded method being called. In my case, this will be the string "CreateItem"

Now for the Problem

Ok, now with all that background I can actually spell out the problem I had to solve. In many cases, I make calls to the CreateItem method many times in a row. So if I need to create three items in the database, I may do something like this in javascript:

MyNamespace.Service.CreateItem("My first Item", 1, OnSucceeded, OnFailed);
MyNamespace.Service.CreateItem("My second Item", 2, OnSucceeded, OnFailed);
MyNamespace.Service.CreateItem("My third Item", 3, OnSucceeded, OnFailed);

Notice that all three calls have the same callback on success. Now lets say I want to create these three items and then as soon as all three calls are completed successfully I want to forward the user to another page. At first you may think I can just do something like this:

function OnSucceeded(result, userContext, methodName) {
    if (methodName == "CreateItem") {
        window.location = "NextPage.aspx";
    }
}

This would forward the user to a new page as soon as our call to CreateItem has completed successfully. There is one huge problem though: how do we know which call to CreateItem succeeded? The first one? The Second one? The third one?

Obviously we only want to forward the user in the case that our final call has succeeded. As you can see, this problem only gets worse if we have other calls on the same page that could be pending at the time we want to forward the user to the next page.

My Solution - Count Your Calls

So here is how I solved the problem: I made a variable which I would use to keep track of how many pending calls there were at any given time. At the top of my javascript page I first declare:

var pendingCalls = 0;

Then, each time I make a call, I increment the counter:

++pendingCalls;
MyNamespace.Service.CreateItem("My first Item", 1, OnSucceeded, OnFailed);
++pendingCalls;
MyNamespace.Service.CreateItem("My second Item", 2, OnSucceeded, OnFailed);
++pendingCalls;
MyNamespace.Service.CreateItem("My third Item", 3, OnSucceeded, OnFailed);

Then I need to make sure I decrement the counter each time a call succeeds or fails:

function OnSucceeded(result, userContext, methodName) {
    --pendingCalls;
}

function OnFailed(error, userContext, methodName) {
    --pendingCalls;
}

This way, we know how many pending calls we have at any given time. Then to forward the user to a new page once all calls are completed, I did the following:

function OnSucceeded(result, userContext, methodName) {
    --pendingCalls;
    if (methodName == "CreateItem" && pendingCalls == 0) {
        window.location = "NextPage.aspx";
    }
}

As you can see, asynchronous programming can be very difficult. Has anybody else had to solve this problem? If so, how did you do it?
Tags:
Categories:
Actions: E-mail | del.icio.us | Permalink | Comments (45) | Comment RSSRSS comment feed

Comments

August 28. 2007 00:33

strofo


          why don't u use the context field? isn't it there just for that?

          if(methodName == "CreateItem" && userContext == 1) window.location = "NextPage.aspx"
        

strofo

August 29. 2007 12:51

Luke Foust

strofo - If I had to do an unknown number of calls then I would still have to store the id of at least the last call made so I would know when to foward to the next page. This would really just be a variation on the solution I am already using. I would need to use some sort of global variable to save and generate a userContext for each call.

Luke Foust

October 9. 2007 05:17

zhuang

use counting is the only way, since last call may not be returned as the last one, it is not as the same sequence as you make the calls

zhuang

July 12. 2010 23:52

Kesley

Many thanks to your information!

Kesley

July 16. 2010 03:35

data cleansing software

i am really appreciating,woow very informative.....great job thank's...!

data cleansing software

July 16. 2010 20:58

genset

everyone needs to get involved

genset

July 17. 2010 14:09

Andrew Collins

Hello ...congrats for the informative post .I'm really glad I found it on googleKeep up the great work because I for sure will check it out for updates

Andrew Collins

July 18. 2010 06:07

table magician

I don't completely agree, but the principle is right, and you're heart is in the right place.

table magician

July 18. 2010 13:45

electronic cigarette

It's crazy this gets written about so little, I'm sure the demand is there.

electronic cigarette

July 20. 2010 08:33

live sex

I am a new visitor of this blog, I like the information found here. I watch your topics every day.

live sex

July 21. 2010 01:41

cash back rebate

It's a beautiful country, more people need to recognise that.

cash back rebate

July 27. 2010 02:00

Jewel Scholes

This is a great post.

Jewel Scholes

July 27. 2010 20:20

Used Computers

Thank you for another fantastic blog. Where else could I get this kind of information written in such an incite full way? I have a project that I am just now working on, and I have been looking for such information... Regards…  http://www.pctechoutlet.com

Used Computers

July 28. 2010 21:06

natural cures for bacterial vaginosis

Here is the 2nd moment I have come across your site in the last couple weeks.  Looks like I ought to bookmark it.

natural cures for bacterial vaginosis

August 3. 2010 09:58

cigarette online

A website with news truly exciting, congratulations to the creator!

cigarette online

August 6. 2010 14:14

cam girls

good references, there were similar discussions on other forums. I'll watch this topic.. <a href="http://www.naughtywebcamsex.com" title="Webcam Girls">Webcam Girls</a>

cam girls

August 6. 2010 18:17

cam girls

Yes, it seems interesting topic. What do you think guys? <a href="http://www.naughtywebcamsex.com" title="Webcam Girls">Webcam Girls</a>

cam girls

August 10. 2010 16:07

Jenifer Emick

Remarkable blog post, plenty of very good details.  I am about to show my buddies and ask them the things they think.

Jenifer Emick

August 15. 2010 14:39

Andre Goldenstein

Wow, I just needed you to know I have added your good site to my Google bookmarks because of your extraordinary blog layout. But seriously, I think your site has one of the freshest theme I’ve came across. It really helps make reading your nice blog a lot easier

Andre Goldenstein

August 18. 2010 02:07

hard drive recovery

Congratulations!You are very profesional.

hard drive recovery

August 18. 2010 05:19

porter cable battery

Hey admin, I like blogengine.net but why did you chose it?  I mean it's so neat with the random avatars and draws people in, but what speficially made you want to use it?

porter cable battery

August 18. 2010 14:09

Isagenix

Great! this is nice article. Thank you for sharing.

Isagenix

August 21. 2010 15:21

Weight Loss 4 Idiots Reviews

Many people will agree with your opinion whoever many other's will not agree,but I appreciate your hard work.

Weight Loss 4 Idiots Reviews

August 22. 2010 16:38

Marisha Degrande

Nice post! I have been looking for this information all around. This is was I looking for.

Marisha Degrande

August 22. 2010 18:19

Online Consignment

Have you ever thought about adding a little bit more than just your thoughts?  I mean, what you say is important and everything.  But its got no punch, no pop!  Maybe if you added a pic or two, a video?  You could have such a more powerful blog if you let people SEE what youre talking about instead of just reading it.

Online Consignment

August 23. 2010 13:12

Online Consignment

Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

Online Consignment

August 27. 2010 12:43

Cursos de inglés

It's the little things that matter, that's what I believe.

Cursos de inglés

August 28. 2010 06:18

Jonah Vangoff

nice blog... why don't you post more?

Jonah Vangoff

August 28. 2010 19:25

Reba Stromski

do you have an rss feed? I want to add it to my reader but I can't find it...

Reba Stromski

August 29. 2010 22:48

funny blonde jokes

how can I advertise on your blog?

funny blonde jokes

August 30. 2010 05:03

seduction affiliate

you may make some money if you add an affiliate program to your blog...

seduction affiliate

August 30. 2010 16:11

joke

nice blog! keep the good work!

joke

August 30. 2010 18:54

how to attract girls

great blog! I too have one ob dating and seduction tips for guys...

how to attract girls

September 2. 2010 00:10

ETF newsletter

it will be great if you post more...

ETF newsletter

September 2. 2010 16:45

Shane Tinnon

great post! i'm bookmarking this!

Shane Tinnon

September 3. 2010 10:44

gift

try to change your template, there are some great ones...

gift

September 3. 2010 17:42

barhocker

Come on guys, let's keep it clean. This is a good blog. Good info mate.

barhocker

September 4. 2010 04:33

dating tips

do you have a xml feed for your blog?

dating tips

September 4. 2010 09:14

ETFs

nice blog, try posting more!

ETFs

September 4. 2010 20:43

schaufensterpuppen

I prefer to look on the brighter side of things which I'm sure you can appreciate.

schaufensterpuppen

September 5. 2010 07:43

Melatonin

No need to be gloomy guys, there's still a lot of positives to take.

Melatonin

September 6. 2010 00:26

ETF newsletters

just bookmarked your blog...

ETF newsletters

September 7. 2010 02:48

electronic cigarette

I like that you've touched on this subject, it's somewhat of a rariety.

electronic cigarette

September 7. 2010 04:26

Carpet Cleaning Philadelphia

I appreciate you sharing this article.Thanks Again. Really Cool.

Carpet Cleaning Philadelphia

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading