Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows:

import {socket} from './socket';

class A{
Execute(...args[]){
   //logic with Promises
   SomeAsyncMethod1().then(fulfilled1);

   function fulfilled1(){
     SomeAsyncMethod2(args).then(fulfilled2);
   }

   function fulfilled2(filled_result){
     //(1)
   }
 }
}

class B{
  private a_obj: A;

  constructor(){
    a_obj = new A();
  }

  Method1(one: string){
    a_obj.Execute(one);
  }

  Method2(one: number, two: any){
    a_obj.Execute(one, two);
  }
}

Class C{
  interface Ids {
    [id: string]: any;
  }
  let instances: Ids = {};
  instances["1"] = new B();
  instances["W"] = new B();

  CallMethod(callerId: string, objectId: string, methodName: string, args: any[])
    instances[objectId][methodName](...args);
    //(!) (2)
  }
}

"(!)" - I aim to transmit the filled_result data from fulfilled2 function to the client using its clientId through the socket. The challenge lies in retrieving both the clientId and the filled_result.

  CallMethod(callerId: string, objectId: string, methodName: string, args: any[])
    instances[objectId][methodName](...args);
    socket.send_results(callerId, filled_result);
  }

The dilemma arises as I lack access to the clientId in (1), similarly, in (2) obtaining the filled_result presents an obstacle.

Answer №1

To solve the issue at hand, I implemented a solution by incorporating a map with requestId (which is generated within the Execute method) as the key. This map is then returned to the parent function that assigns a clientId to the map using the provided key.

import {socket} from './socket';

interface IStringMap {
  [key: string]: any;
}
const REQUEST_QUEUE: IStringMap = {};

GenerateRequestID() {
    return Math.random().toString(36).substr(2, 9);
}

class A{
   Execute(...args[]):string {
     let req_id = this.GenerateRequestID();

     // logic involving Promises
     SomeAsyncMethod1().then(fulfilled1);

     function fulfilled1(){
       SomeAsyncMethod2(args).then(fulfilled2);
     }

     function fulfilled2(filled_result){
       socket.send_results(REQUEST_QUEUE[req_id], filled_result);
       delete REQUEST_QUEUE[req_id];
     }

     return req_id;
   }
}

class B{
  private a_obj: A;

  constructor(){
    a_obj = new A();
  }

  Method1(one: string){
    return a_obj.Execute(one);
  }

  Method2(one: number, two: any){
    return a_obj.Execute(one, two);
  }
}

Class C{
  interface Ids {
    [id: string]: any;
  }
  let instances: Ids = {};
  instances["1"] = new B();
  instances["W"] = new B();

  CallMethod(callerId: string, objectId: string, methodName: string, args: any[]) {
    let reqId = instances[objectId][methodName](...args);
    REQUEST_QUEUE[reqId] = callerId;
  }
}

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

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

The output of JSON.stringify() when given a single value as input

The JSON.stringify() function is designed to convert a JavaScript value into JSON format. console.log(JSON.stringify('a')); //output: "a" console.log(JSON.stringify(1)); //output: 1 console.log(JSON.stringify(true)); //output: true However, tec ...

Transferring variables from EJS to JavaScript on render (server to client) securely to prevent cross-site scripting vulnerabilities

When passing variables to JavaScript using ejs, the accepted method often looks like this: <script> var foo = <%- JSON.stringify(foo) %>; </script> However, there have been issues with XSS vulnerabilities using this approach. Is there ...

Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right! function ClassName(productId) { ...

Activate the button with a tap of the space bar on a webpage

Is it possible to have a button on a webpage triggered both by clicking with the mouse and hitting the spacebar? HTML <div class="col-12 button small-button"> <a onclick="generator()"> <img src="icones%20web%20projeto.p ...

Preserving the <script> tag when defining HTML code

During an AJAX call, I am receiving plain HTML with some JavaScript code. When I try to display this response in a container using .html (jQuery) or innerHTML (plain JavaScript), it removes the <script> tag and all JavaScript code. However, when I c ...

Unable to access property within JSON object sent via POST request

I encountered an issue TypeError: Cannot read property &#39;tasks&#39; of undefined While attempting a new POST request on my API, here is the request body I am using: { "name": "example1", "description": "teaching example1", "rules" ...

The jQuery ajax function functions flawlessly on a local environment, but encounters issues when used on a

After spending the entire day researching this issue, it appears to be a common problem without a solution in sight. The challenge I am facing involves using jquery's $.ajax() function to update database values through a service call. While it works ...

Incorporating a Registration Popup Form in ASP.NET

Looking to implement an Ajax popup for a registration form on my ASP.NET page. What is the recommended approach to achieve this? How can I ensure that my database is updated without needing to refresh the page? ...

The query does not produce a match when using the LIKE operator with the retrieved ajax data

My goal is to sync up profiles in my MySQL database with the names and skillsets dropped into my droppable div. At this link, you can find a snippet of code for reference. I am facing two main issues - firstly, the error message mysql_fetch_array() expects ...

Customizing SwiperJS to display portion of slides on both ends

I need some assistance with my SwiperJS implementation to replace existing sliders on my website. The goal is to have variable-width slides, showing a landscape slide in the center with a glimpse of the preceding and following slides on each side. If it&ap ...

Please refrain from refreshing the page multiple times in order to receive updated data from the database

Currently, I have created a countdown timer from 00:60 to 00:00. However, once the timer reaches 00:00, I am looking to refresh the page only once in order to retrieve a new value from the database. Does anyone have any suggestions on how to achieve this ...

Retrieve the link of a nearby element

My goal is to create a userscript that has the following functionalities: Add a checkbox next to each hyperlink When the checkbox is clicked, change the state of the corresponding hyperlink to "visited" by changing its color from blue to violet. However ...

Is it beneficial to vary the time between function calls when utilizing setInterval in JavaScript?

My website is displaying two words one letter at a time, with a 0.1s delay between letters and a 3s pause after each full word. I attempted using setTimeout, but it's not functioning as expected. What could be the issue in my code? var app = angular. ...

Is there a way to efficiently convert several strings within an object that has been retrieved from an HTTP request into another language, and subsequently save this object with the

Is there a way for me to translate some strings in an object before storing it in another http request using the Google Translate API? I am currently getting the object from one http request and saving it with a put method. How can this be achieved? servi ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...

Is there a way to showcase a PDF file using pdftron through npm?

pdftron/webviewer has been successfully installed "dependencies": { "@pdftron/webviewer": "^7.3.0", "body-parser": "^1.19.0", "express": "^4.17.1", ...

I have the ability to effectively open a modal whenever necessary, but I struggle with closing it afterwards

I've been working on implementing a React bootstrap modal, and while I can successfully open it when needed, I'm running into issues with closing it. I'm not sure what mistake I might be making. Here's my markup: <Modal show={this. ...

Unusual situation involving the override of a function pointer variable

Let's explore a straightforward scenario: (function x(){ var foo = function(){ console.log('foo is alive!'); // set 'foo' variable to an empty function, using a delay setTimeout(function(){ foo = function(){}; ...

Difficulty in jQuery's clone() function: cloning an input element without its value

I have successfully implemented jquery's .clone() method, but I'm facing an issue where the value of the previous input field is also getting cloned along with it. How can I prevent this from happening? Below is my code snippet: function addrow ...