0

i create an short example and i have a dubt:

var request = require("request");
var url = "http://api.openweathermap.org/data/2.5/weather?q=turin&APPID=xxxxxxxxxxxxxxxxxxxxxx";
module.exports = function (callback) {

    request(
    {
        url: url,
        json: true
    }, function (error, response, body) {
        if (error) {
            callback("Unable to fetch weather"); // callback function
        } else {
            callback("It is " + body.main.temp + " in " + body.name);
        }
    });

    console.log("After request");
};

And from external file, i required this module:

var weather = require("./weather.js");

weather(function (currentWeather) {
    console.log(currentWeather);
});

In this case, i call a weather module and i get a callback function ( it is an argument of weather module ) for print into command line the weather in Turin. But how it's work?

Morris
  • 601
  • 1
  • 8
  • 22

1 Answers1

1

i call a weather module and i get a callback function ( it is an argument of weather module ) for print into command line the weather in Turin. But how is possible?

Functions in Javascript are a first class object means that you can store a function into a variable and pass it into another function. This pattern is very common on Node.js and in Javasript in general, this is called the Continuation passing style ( CPS )

Hope it helps.

Community
  • 1
  • 1
Marwen Trabelsi
  • 4,167
  • 8
  • 39
  • 80