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?

2
  • 3
    It's not clear what you're asking. The export of weather.js is a function. You call that function with a callback function parameter. Commented Oct 18, 2016 at 16:26
  • "But how is possible? " I think his real question is "how it's work?".. Commented Oct 18, 2016 at 16:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Clear! Thank you so much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.