Thursday, June 21, 2018

JavaScript - Method to Call Backend Logic in Sequential Loop

When we call backend REST service from JavaScript - call by default is executed async. This means it will not wait until response from backend is received, but will continue executing code. This is expected and desired functionality in most of the cases. But it might be requirement, where you want to call backend in synchronised way. Example - calling backend service multiple times in the loop, next call must be invoked only after previous call is complete. With default async functionality, loop will complete before first REST call.

Here is the example of calling backend REST service (through Oracle JET API, using JQuery in the background). Call is made 3 times, with success callback printing a message. One more message is printed at the end of each loop iteration:


Three backend REST calls are executed in the loop:


Loop completes earlier than REST call from the first iteration, we can see it from the log:


It might be valid and expected behaviour for most of the cases. But depending on backend logic, may be you would like to guarantee no call from second iteration will be invoked, until first iteration call not complete. This can be achieved by specifying async function and using Promise inside the loop. We should use await new Promise syntax and resolve it in success callback by calling next():


With promise applied, loop is executed sequentially - next loop iteration is started, only after backend service success callback is invoked. You can see it from the log:


Source code is available on my GutHub repository.

No comments: