March 25

jQuery promises

Sometimes it is required to execute callback right after the last of related Ajax call is completed. In this example there are 6 div elements (result1, result2, result3, result4, result5 and totals). There is external PHP script (call.php) which returns random number. Result DIV elements are populated asynchronously. Totals DIV element should contain sum of result DIV elements.

Ajax request is sent 5 times but it is unknown which request will be at the end. So it is questionable where to put code for calculating totals. Although setTimeout or global Ajax events can be utilized we should avoid them because of unpredictable results.

Fortunately, there is a JavaScript Promises functionality. jQuery has its own implementation which is well integrated with Ajax event handlers.

Callback function inside done() event will always execute right after last Ajax call.

Please follow and like us:



Posted March 25, 2016 by mmedojevic in category "JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *