JavaScript: Converting a Callback to Promises

Callbacks

For JavaScript to know when an asynchronous operation has returned a response (the response could be an correct result or error response), it points to a function that will be executed once that result is ready.

This function is what we call a “callback function”.

In a simple way, a callback is a function that is passed to another function. When the first function is done, it will run the second function.

Here is our call back function

Screenshot (51)
callback function called in request function

 

 

Promises

A promise is an object that wraps an asynchronous operation and notifies when it’s done.

Similar to callbacks, the implementation is a bit different.

Instead of providing a callback, a promise has its own methods which you call to tell the promise what will happen when it is successful or when it fails.

The creation of a Promise object is done via the Promise constructor by calling “new Promise()”.

It takes a function as an argument and that function gets passed two callbacks: one for notifying when the operation is successful (resolve) and one for notifying when the operation has failed (reject).

Screenshot (52)
Creating a Promise 

 

Next topic will about Callback Hell and how Promises can be used to solve them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s