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
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 items
array.
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.