Writing your own callbacks in JavaScript and Node.js

Shivam Gupta
3 min readAug 29, 2018

--

JavaScript custom callback by- Shivam Gupta

callback sometimes became more complex for beginners as well as experienced so here we will try to understand about callback and some basic example of callback. and also creating own callback method.

What is Callback ?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. (source- MDN)

In callback we pass some data and wait for the response of that data when response came so callback method executed as success or failure.

Syntax -

functionName (data, ()=>{ // this is callback block

})

The anonymous method pass inside function parameter is known as callback it executes when requested data get something back.

Example -

setTimeout(()=>{

// This callback will be executed after 2 seconds
},2000)

Basic Example

Example Callback

Lets Do some cool thing — create our first callback

Example

let getResponse = (data, callback) => {

if(data.name == ‘Shivam’) {

callback(undefined, ‘Hello Sir Its you ! Welcome’)

} else if (data.name == ‘’) {

callback(‘Name can not be blank’); // send error message

} else {

callback(undefined, ‘Someone else is trying to login !!’) // undefined — no error

}

}

Here First create a method which will handle callback and this is very basic conditions. so getResponse method accept 2 params 1 to take input and when success so provide output.

let data = {name: ‘Shivam’, address: ‘New Delhi’}

getResponse(data, (errorMessage, results) => {

if(errorMessage) {

console.log(errorMessage)

} else {

console.log(‘result : ‘,results)

}

})

Output —
result : Hello Sir Its you ! Welcome

if data = {name:``}

Name can not be blank

So This was very basic example of callback, in real world we use callback in like -

we get HTTP response from an api in a file -geocode.js , it contains method definition of getGeocodeAddress() , and calling of this method from app.js so in app.js we just pass request data and wait for callback. See an working example of node.js —

app.js

const geocode = require(‘./geocode/geocode’);

geocode.getGeocodeAddress(`New Delhi, India Gate, India`, (errorMessage , results)=> {

if(errorMessage) {

console.log(errorMessage)

} else {

console.log(JSON.stringify(results, undefined, 2)); // undefined- formatting function not needed

}

});

geocode.js

const request = require(‘request’);

var getGeocodeAddress = (address, callback) => {

var encodedAddress = encodeURIComponent(address)

request({

url: `https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAo7a_I25OCt8lRD6jKMAQWhRHejYcKOm9&address=${encodedAddress}`,

json: true

},(error, response, body)=>{

console.log(JSON.stringify(response, undefined, 2));

if(error) {

callback(‘Unable to connect to Google servers.’)

} else if (body.status == ‘ZERO_RESULTS’) {

callback(‘Unable to find that address.’)

} else if (body.status == ‘OK’) {

callback(undefined, {

address: body.results[0].formatted_address,

latitude: body.results[0].geometry.location.lat,

longitude: body.results[0].geometry.location.lng

})

} else if (body.status == ‘OVER_QUERY_LIMIT’) {

callback(‘Over query limit !’)

}

})

}

module.exports.getGeocodeAddress = getGeocodeAddress;

Thank you and please give comments and suggestions .

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

No responses yet