Sure, here's the corrected and rewritten version of the text:
Yo, listen up! When a function accepts another function as an argument, that contained function is called a callback function. Using callbacks is a core functional programming concept. It's like calling your bestie to ask for help, and they call you back with a solution.
Node, on the other hand, is basically built to be asynchronous in everything it does. That's why callbacks are expected as arguments rather than returning data in most of the internal Node APIs. It's like Node is always multitasking, and callbacks help it manage its tasks.
Let's check out some code to understand callbacks better. In the following example, we're using the readFile
method of the file system, which is asynchronous. Once the file is read, the callback method will be called. See the code below:
// Callback function.
var fileCallback = function(err, data) {
if (err) return console.error(err);
console.log(data);
}
// Takes a callback as a parameter. Once the readFile is done, the callback function will be called.
var fs = require('file-system'); // npm install file-system --save
fs.readFile('words.txt', fileCallback);
Another example is using the npm package node-geocoder
to get the latitude and longitude of a particular zipcode. Here's the code:
var NodeGeocoder = require('node-geocoder'); // npm install node-geocoder --save
var options = {
provider: 'google',
httpAdapter: 'https',
formatter: null
};
var geocoder = NodeGeocoder(options);
var data = [];
// Takes callback as one of the parameters.
var getGeoData = function(zipcode, callback) {
geocoder.geocode(zipcode)
.then(function(res) {
var lat = res[0]['latitude'];
var long = res[0]['longitude'];
data.push(lat);
data.push(long);
// Return error as null with data as the second parameter.
callback(null,data);
})
.catch(function(err){
// Return error with data as null.
return callback(err,null);
});
};
var getGeoDims = function(zip) {
// (err, list) is the callback we are passing.
getGeoData(zip, ((err, list) => {
if(err) return console.error(err);
else return console.log("Everything went fine!");
}));
};
getGeoDims(94025);
We invoke the getGeoDims
function. It calls the getGeoData
function that takes the zipcode and callback function as parameters. We could have defined the callback function as in the above example. It's like calling a pizza delivery guy and telling them your address and the pizza you want, and when the pizza arrives, they call you back.
If you want to learn more about callbacks, promises, and async, check out this link: callbacks-promises-and-async. It's like a whole treasure trove of knowledge waiting for you!