There are times (like the one I ran into today) where you don't want an ajax request to be asynchronous. By default all ajax requests are set to asynchronous by default which can cause some strange behavior if your'e not paying attention. I am going to create a really basic example here that should outline the problem. First we have a basic template that allows the user to enter their name, click a button and somewhere we will write some output to the container div. Next I will setup a click handler on our button. We will get the name of the user by grabbing the value of our input box. Finally we will call a get messages function that will contain the logic to get our messages. That method will return an array and we will loop over that array and print the messages to our container div.
Now its time to build out our get messages function. First lets just start by adding some static messages to an array and returning that.
This works great so far but I forgot that one of my messages in api call somewhere else. I need to make a request to this API and it will return another message for me to add to my messages array.
So everything looks pretty good here right? The problem is our program still only prints out our first 2 static messages. If you remember to the beginning of this post I mentioned that all ajax request are asynchronous by default. So while our program is talking to our API execution is returned to our program and the 2 static messages are returned. There are a couple approaches to solving this but the easiest is making our ajax request synchronous and to do that all you have to do is set the async property of the ajax method to false. Then your request will finish, return and you can add your new messages to the messages array. Simple example but important to understand.