0

I met a problem recently: How can i assign value to a global variable?

when i try to return a, i found that is undefined, and the "value" i wanna to assign to it is not undefined.

my code is like this:

module.exports = function (jsonStr) {
    var a;
    request(main_url, function(error, response, html) { 
        if(!error) {
           ...
           request(sub_url, function(error, response, html) { 
               if(!error) {
                  ...
                  a = value;
                  ...
               }
           }
         }    
    } 
    return a;   
});
Leyla Lee
  • 466
  • 5
  • 19
  • replace "var a" with "". but, btter, don't use globals; tack the stuff onto `exports` as needed. – dandavis Oct 06 '15 at 16:42
  • That is because `a = value` gets executed asynchronously (the assignment happens **after** your function on `module.exports` finishes execution). What you should do is have a callback on your function that has `a` as an argument. (For example, `function(jsonStr, callback)`) – JCOC611 Oct 06 '15 at 16:42
  • http://stackoverflow.com/questions/32407269/why-cant-i-see-this-json-in-the-console – Soren Oct 06 '15 at 16:45
  • @JCOC611 Omg, after? ah, that's why, i will check my logic again. Thank you ! – Leyla Lee Oct 06 '15 at 16:46
  • @JCOC611 sorry, i tried, but i still failed to return a, i was totally confused about how to return it. T.T can u help me? – Leyla Lee Oct 07 '15 at 10:03

1 Answers1

0

The problem there is that your request function is asynchronous, and then, the return a statement will occur before you set a = value.

One way to achieve what you want is by using the asyncawait library, something like:

module.exports = async(function (jsonStr) {
    var a;
    var sub_url = await(request(main_url));
    a = await(request(sub_url));
    return a; 
});

Take a look at this QA.

Community
  • 1
  • 1
Buzinas
  • 11,597
  • 2
  • 36
  • 58