What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation.

Currently, I'm working on a simple node application that retrieves stock prices from one web API, fetches currency conversion rates from another API, and then converts the stock price from USD to AUD. Initially, everything worked perfectly when all the code was in a single file. However, in an effort to simplify things, I decided to divide it into multiple modules and now I seem to have broken it :)

Essentially, I pass the desired ticker symbol into my GetStockPrice() function, which then executes the necessary query and returns the result... in theory.

This is how I call my module:

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

Unfortunately, the returned value always remains 10 because it's not being updated within my GetStockPrice module.

Here's the code within 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;

My understanding is that the issue lies with the asynchronous nature of http.request. By the time my function reaches the return statement, the async call hasn't completed yet, so the return value (stockPrice) remains the same as when it was initially initialized. Unfortunately, I'm unsure how to resolve this. I attempted to move the return statement inside the http.request function, but that didn't yield any successful results either.

If anyone has any guidance or assistance, I would greatly appreciate it!

Answer №1

To obtain responses from asynchronous functions, you can make use of callbacks.

const http = require('http');
let stockPrice = 10;


function fetchStockPrice(ticker, callback){
   const 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');
      let retrievedStockPrice='';
      res.on('data', function (chunk) {
        retrievedStockPrice += chunk;
      });
      
      res.on('end', function(){
          return callback(JSON.parse(retrievedStockPrice));     
      });
   });
}

module.exports = fetchStockPrice;

Furthermore,

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

Please excuse any typographical errors that may have occurred.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simplified JavaScript Object Structure

A JSON array that is flat in structure looks like this: var flatObject = [ { id : "1", parentId : "0", name : "object 1" }, { id : "2", parentId : "1", name : "object 2" }, { id : "3", parentId : "2", name : "object 3" }, { id : "4", pare ...

Serve old links using Express.js (with .php extension)

I'm currently in the process of migrating a PHP application to node/express. One issue I'm encountering is serving legacy links such as www.example.com/test.php. When trying to access these links, express returns the error: Cannot GET /test.php ...

Issue with populating dropdown menu inside jquery modal dialog box

When I click on the 'create new button', a modal window form pops up with a dropdown menu. The dropdown is supposed to be populated via ajax with the help of the populateUserData() function. Even though the ajax call seems to be successful, I am ...

When I try to make an on-demand revalidation API call on Vercel, it takes so long that it ends up timing

Inspired by Kent C. Dodds, I have created a blog using Github as my Content Management System (CMS). All of my blog content is stored in the same repository as the code, in mdx format. To streamline the process, I set up a workflow that detects changes i ...

Module not found even after executing npm install within Docker container

I am currently in the process of Dockerizing a node application, but I'm encountering an issue when attempting to start the app using: docker-compose -f docker-compose -f docker-compose.override.yml An error message stating ** Error: Cannot find mod ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

What is the reason for Slack displaying the Node.js response JSON in its raw form?

When sending a JSON response from my Node.js server to a Slack App, I encountered an issue where the response is displayed in raw form as JSON instead of being properly formatted. To replicate the problem, here is the minimum code needed: server.js: ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

Troubleshooting the Confirm Form Resubmission problem on my website

Hello everyone! I'm working on a website and facing an issue where refreshing the page triggers a confirm form resubmission prompt. Could someone please advise me on how to resolve this? Thank you in advance! ...

Auto-refresh the page upon any updates made to the MongoDB collection

I'm currently working on a Node.Js project that involves MongoDB integration. I'm looking for a way to automatically refresh one of my HBS pages whenever there is a change in my MongoDB collection. I could use some guidance on the best approach ...

Corrupted Attachment in Azure Function Sendgrid Integration

Currently, my setup involves Azure Functions and node.js working with Sendgrid to send emails to users when specific PDF blobs are uploaded to our blob repository. While everything has been functioning properly so far, I am facing an issue when trying to a ...

Issue with jQuery fadeIn() and fadeOut() functions on IE versions 7 and 8

I have a project in Ruby on Rails that showcases illustrations. The top of the page features category links that fade out the current illustrations, replace them with new content, and then fade back in. Currently, I am utilizing jQuery version 1.6.2 for t ...

What is the process for aligning rows with the selected option from the drop-down menu

Alright, so here's the scenario: I have created a table along with two drop-down filters. The first filter is for selecting the Year, and it offers options like "All", "2023", "2022", and "2021". When I pick a specific year, let's say "2022", onl ...

Disabling hover effects in Chart.js: A step-by-step guide

Is there a way to disable hover effects, hover options, and hover links on a chart using chart.js? Here is the code I have for setting up a pie chart: HTML.. <div id="canvas-holder" style="width:90%;"> <canvas id="chart-area" /> </div ...

Error in AngularJS ng-repeat syntax

As a newcomer to AngularJS, I ventured into creating a Bootstrap form with a loop but encountered an error. What could be the mistake I made? <form class="form-horizontal" role="form" name="newForm" novalidate ng-controller="newFormController"> < ...

Learn how to extract IMG SRC using web scraping with cheerio in node.js

Implementing an event listener to FETCH this and using cheerio to extract the img src from: <div class="mainimage"> Existing script: var cheerio = require('cheerio'), $ = cheerio.load(this.responseText); console.log($('mainimage&apo ...

Steps to display the datatable footer on the printed page

I am having trouble understanding the solutions provided for my table query. The current table setup is as follows: <table class="table table-bordered make_datatable"> <thead> <tr> <th>SL No</th> ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

Encountering an error during the registration process of @fastify/middie

I am currently in the process of integrating Fastify into a small project I am working on. One of the key requirements for this project is the utilization of Middleware (via @fastify/middie). However, when I follow the necessary steps to register the middi ...