Callback function

Vignesh S
2 min readMay 2, 2021

--

Table of Contents

callback function

A function with an argument of another function to be a callback. eg) function(arg1, callback).

Use of callback function

Sometimes your function fully depends upon the data which u received from another function. In such cases, the callback will help the outer function will wait till the callback should complete their actions, and then the outer function will perform the routine or actions.

Simple Callback

In the example below, the method employeeData is collecting data from the callback method of getProfile and this again has a callback of getTechProfile. This means the outer function of employeeData waits for the callback methods has to execute, then the outer function will return the value. Code Pen

If a function depends on a limited callback in such case the callback for the code is simple and easy to understand as well as maintain.

Multiple Callbacks

Suppose if there are multiple callbacks (nested dependent) is required, In the below example, the outer function of initialFn has to wait for the callback add, even add method also has a callback subtract and the callback chain goes to multiply from subtract.

Multiple Callback workflow

In the example above, there are more nested callbacks, which are very hard to understand and maintain. To overcome this problem promise came. Let’s see what is a promise and how it helps?

Hope it will give a clear view of callback functions, Please write your questions for any doubts or corrections.

Let’s discuss the next feature of ES6 in the next story.
Next topic: Promises

--

--