OpenSource For You

JavaScript callbacks

-

JavaScript began as a browser language, with the primary task of handling user events such as a mouse click. The language has excellent support for event-driven programmin­g. In this language, functions are first class citizens, which means you can use a function where any other primitive data type fits. For example, a function can be passed as an argument. A function can also return a function. A callback is a function that will get executed upon an event. It is common for frontend developers to write many callback functions on mouse events like onClick, onmousedow­n, etc. The functions (callback) get called upon mouse events.

Another important point to note is that JavaScript is single-threaded. Any operation (function call), which takes time, should be asynchrono­us.

Let’s take an example of a callback.

Line 2: Creates a new Promise object. The object ‘p’ gets a value after reading the file.

Line 3: A Promise takes a function. The function in turn takes two functions ‘resolve’ and ‘reject’ as parameters. For all successful cases, it executes ‘resolve’. For error scenarios, the second parameter function is executed.

Newspapers in English

Newspapers from India