0

I have the following two files and can't get the result out of my modules request into the var inside app.js.

I thought about module.exports exports as callbacks but I can't find the right combination.

// app.js

#!/usr/bin/env node

// i am a nodejs app
var Myobject = require('./code.js');

var value1 = "http://google.com";

var results = Myobject(value1); // results should stare the results_of_request var value 

console.dir(results); // results should stare the results_of_request var value 

now comes the module // code.js

// i am a nodejs module
module.exports = function(get_this) {
  var request = require('request');
    var options = {
          url: get_this,
    };



  request(options, function(error, response, body) {
            if (!error) {
               // we got no error and request is finished lets set a var
               var result_of_function = '{"json":"string"}'
            }
    }
// the main problem is i have no way to get the result_of_function value inside app.js
}
1
  • Only for Documentation i asked this question because many People that are new to JavaScript are not familar with the Callback Pattern if they don't heard about that befor. Commented Oct 2, 2018 at 5:00

1 Answer 1

1

As your exported function from your module is asynchronous, you need from your app to handle its result via a callback In your app:

Myobject(value1, function(err, results){
  //results== '{"json":"string"}'
});

In your module:

module.exports = function(get_this, cbk) {
  var request = require('request');
    var options = {
          url: get_this,
    };

  request(options, function(error, response, body) {
            if (error) {
               return cbk(error);
             }
             // we got no error and request is finished lets set a var
             var result_of_function = '{"json":"string"}'
             return cbk(null, result_of_function)
    }
// the main problem is i have no way to get the result_of_function value inside app.js
}
Sign up to request clarification or add additional context in comments.

Comments

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.