wait for async code in a callback function

Situation

We have a function that does some processing. Then it executes a callback function.

So say we call function A, and provide an anonymous callback function.

Under this case, we will get the true in function A’s definition.
Everything is synchronous so we go step by step.

The Problem

The problem happens when we have asynchronous code in our callback

Given definition A:

In our callback definition, we do something asynchrnous. It returns true after 2 seconds.

This is a problem because while the execution is happening for the setTimeOut of waiting 2 seconds, our main execution
continues and our reply will be undefined.

The Solution

The solution is to use Promises. In this particular case, I will use jQuery’s Deferred, which is exactly the same as Promise, except its packaged in jQuery’s API.

1) chain the ‘then’

In order to wait for the async to finish, we call the callback function, and then chain the API call ‘then’ in order to continue with the results. This is assuming we declared a Promise object and returned it in cbConfirmed(). (we’ll get to this in the next step)

When you chain the then call, it will wait for async code to finish, then you simply provide an anonymous callback function inside to get the results.

2) declare and return the Promise object

3) call resolve and use it where the async code has finished

The main execution will wait for the callback to finish. After 2 seconds, the callback returns and gives the result to function A.