In a recent project, there was a need to make ajax calls to a remote server in a sequential manner to synchronise data. Each call would wait for the previous one to complete, before triggering the next one. To achieve this, I used jQuery and Promises together create the below code.
The code below makes uses of Promises in jQuery to wait for ajax calls to complete before starting the next call in the sequence. All the ajax calls are made to the same API, but the data sent in the call are defined in the
On line 34-41, we use the jQuery
$.map functions to cycle through the items in the
items array, and then call an ajax function. When all the items in the array have been processed, the jQuery
$.when.apply function allows us to trigger a final callback (lines 41-44).
This code is useful when you need to upload a number of items to a server in sequence, for example, uploading images from the user’s device one at a time. If we sent all the images in one go, it would not only slow down the user’s device, but it could also overwhelm the server. So, making the calls sequentially can help manage the situation.
Let me know if you have any questions or issues in the comments section below.
Thanks for publishing the example, it’s just what I need. Its interesting to see how you have been able to make the requests sequential using the ‘looper’ deferred variable.
thanks for publishing this example. I have project where to made a db call more that 100000 times and get the response until all the queries are done , what would be the best approach to do so. The db calls must be done sequentially one by one in other to over system saturation .
Thats a lot of DB calls to make using Ajax. You should consider using another method like queue instead, because if one if these calls fail, you won’t be able to restart from the failed call.
Does it pay to run the ajax calls in batches, for instance 5-10 at a time? I have 50 images that I GET from my server. I am going to try your code for this, 1 at a time as you show, but just wanted your opinion on doing it in batches. Thoughts? Thanks, great article, thanks you.
FYI – It is better! 🙂 Thank you for this article, well done!
Thanks in 2021. I was able to make sequential uploads with your example.