1

I have two files where one.js has all modules and those modules are called in two.js file. But whenever I do get request, the function does not wait. I know node is asynchronous. Is there any way to handle the function without callbacks

//File one.js
function getRequest(){
var url = "https://api.hasoffers.com/v3/Affiliate_Affiliate.json";
        request(url, function (err, reponse, value) {
            return JSON.parse(value);
        });
}
exports.getRequest = getRequest;

//File two.js
var one = require(one.js);
console.log(one.getRequest()); //Returns undefined  

I need to call function in two.js file in the same way one.getRequest(); without any callback.

George Kagan
  • 5,913
  • 8
  • 46
  • 50
user4324324
  • 559
  • 3
  • 7
  • 25

2 Answers2

0

you need to use promise or callback

function getRequest(callback){
var url = "https://api.hasoffers.com/v3/Affiliate_Affiliate.json";
    request(url, function (err, reponse, value) {
        callback(JSON.parse(value));
    });
}

//File two.js

var one = require(one.js);
one.getRequest(function(result){console.log(result)});
fingerpich
  • 8,500
  • 2
  • 22
  • 32
  • I know about callbacks but I have mentioned in my question that I need to call one.getRequest(). Is there any way to handle the result in one.js file ? – user4324324 Nov 12 '16 at 10:55
  • with this answer you handle the result in one.js, but with a function defined in two.js – erwan Nov 12 '16 at 11:01
0

you can use something like this:

//File one.js
function getRequest(){
 this.url = "https://api.hasoffers.com/v3/Affiliate_Affiliate.json";

}
getRequest.prtotype.request=function() {
       request(this.url, function (err, reponse, value) {
        return JSON.parse(value);
    }); 
 });
 exports.getRequest = getRequest;



//File two.js
var one = require(one.js);
one=new one ();
 console.log(one.request()); 
farhadamjady
  • 982
  • 6
  • 14
  • if I add one more function inside one.js file, it throws me error like this.errorRes is not defined. getRequest.prototype.errorRes = function (msg) { //Some object formation return JSON.parse(msg); }; and use the same inside getRequest.prtotype.request=function() { request(this.url, function (err, reponse, value) { if(err){ return this.errorRes(error);} return JSON.parse(value); }); }); – user4324324 Nov 21 '16 at 11:12