title: Returning a value from callback function in Node.js
body: <p>I am facing small trouble in returning a value from callback function in Node.js, I will try to explain my situation as easy as possible. Consider I have a snippet, which takes URL and hits that url and gives the output:</p>
  
  <pre><code>urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
      var statusCode = response.statusCode;
      finalData = getResponseJson(statusCode, data.toString());
  });
  </code></pre>
  
  <p>I tried to wrap it inside a function and return a value like this:</p>
  
  <pre><code>function doCall(urlToCall) {
  urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
      var statusCode = response.statusCode;
      finalData = getResponseJson(statusCode, data.toString());
      return finalData;
  });
  }
  </code></pre>
  
  <p>Because in my Node.js code, I have a lot of <code>if-else</code> statement where value of <code>urlToCall</code> will be decided, like this:</p>
  
  <pre><code>if(//somecondition) {
     urlToCall = //Url1;
  } else if(//someother condition) {
     urlToCall = //Url2;
  } else {
     urlToCall = //Url3;
  }
  </code></pre>
  
  <p>The thing is all of the statements inside a <code>urllib.request</code> will remain same, except value of <code>urlToCall</code>. So definitely I need to put those common code inside a function. I tried the same but in <code>doCall</code> will always return me <code>undefined</code>. I tried like this:</p>
  
  <pre><code>response = doCall(urlToCall);
  console.log(response) //Prints undefined
  </code></pre>
  
  <p>But if I print value inside <code>doCall()</code> it prints perfectly, but it will always return <code>undefined</code>. As per my research I came to know that we cannot return values from callback functions! (is it true)? If yes, can anyone advice me how to handle this situation, as I want to prevent duplicate code in every <code>if-else</code> blocks.</p>