1

Forgive me, but as an extremely new developer I fail to see how this is an exact duplicate of the questions referred to. I have no idea what ajax is, and I certainly don't understand how to adapt the proposed solutions to work in my situation.

I'm writing a very simple node app that gets a stock price from a web api, get a currency conversion value from another web api, and converts the stock price from USD to AUD. I had this working perfectly in a single file, but I've chosen to split it out in to several modules to make it easier. And now I've broken it :)

Basically I pass the ticker I wish to lookup into my GetStockPrice() function, which then perform the necessary query and returns the result.....in theory.

This is how I call my module:

var returned = GetStockPrice('AMZN');
console.log(returned);

The returned value is always 10, as it's not being updated in my GetStockPrice module.

Here is the code in my module:

var http = require('http');
var stockPrice = 10;

function GetStockPrice(ticker) {
  var options = {
    host: 'dev.markitondemand.com',
    port: 80,
    path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker,
    method: 'GET'
  };
  http.request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      const json = JSON.parse(chunk);
      stockPrice = json.LastPrice;
    });
  }).end();

  return (stockPrice)

};

module.exports = GetStockPrice;

I understand what I'm doing wrong, the http.request is being run asynchronously, so by the time my function gets to the return statement, the async call hasn't completed, so my return value, stockPrice, is still the same as when I first initialized it. Unfortunately, I don't know how to fix it. I tried moving the return statement inside the http.request function, but that doesn't work either.

Can anyone help please?

Kelly Norton
  • 487
  • 2
  • 4
  • 19
  • 2
    Async begets async: there is *no value yet*. Promote the pattern *all* the way through; preferably with Promises or ReactJS - using explicit callbacks as needed to glue into node itself (but there are nice promisify-wrappers). – user2864740 May 31 '16 at 05:19
  • It may look like a duplicate to both of you, who have thousands of posts under your belt, but to a brand new developer with 15 posts, it's like comparing an apple and an orange. How about taking a second to remember what it was like being a new developer before making such decisions. So this may be similar to another post, that doesn't mean I can answer my question looking at that post, and still really need help with MY problem. – Kelly Norton May 31 '16 at 19:32
  • Programming involves identifying problems, generalizing solutions, and applying the knowledge to the specific situation. If after reading through other posted replies there are remaining issues/questions, then ask for specific clarification on certain points - preferably with supportive references. The question with 2000+ votes explains the exact problem and leads to the next step. It is best not to take SO too personally :} – user2864740 May 31 '16 at 23:42

1 Answers1

0

You can use callback to get response from asynchronous functions.

var http = require('http');
var stockPrice = 10;


function GetStockPrice(ticker, callback){
   var options = {
      host: 'dev.markitondemand.com',
      port: 80,
      path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker,
      method: 'GET'
   };
   http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      res.setEncoding('utf8');
      var stockPrice='';
      res.on('data', function (chunk) {
        stockPrice = stockPrice + chunk;
      });
      res.on('end', function(){
          return callback(JSON.parse(stockPrice));     
      });
   });
};

module.exports = GetStockPrice;

And

GetStockPrice('AMZN', function(data){
   console.log(data);
});

Pardon me, if there are any typos.

Mukesh Sharma
  • 8,914
  • 8
  • 38
  • 55