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

What is the reason behind VS Code not showing an error when executing the command line tsc shows an error message?

Deliberately introducing a typo in my code results in an error. Here is the corrected code: declare const State: TwineState; If I remove the last character and then run tsc on the command line, it throws this error: tsc/prod.spec.ts:7:22 - error TS2304: ...

The website functions properly in Chrome, but encounters issues in IE

Currently working on validating some JavaScript code. Chrome seems to be handling it well, but as expected, IE is causing some issues. Take a look at the code below: function validateData(a,id){ var inputs = document.getElementsByName('attname[] ...

Synchronize custom directive controller data with data from a factory

As a newcomer to angularjs, I stumbled upon this example that I found somewhere and it works perfectly well. However, I am puzzled by how the data within the customized directive controller remains synchronized with the factory data. Here is the snippet of ...

Encountering an 'Unknown provider' error while running a unit test with AngularJS and Jasmine

I am facing an issue while writing a unit test for a controller in my application. Jasmine is showing an 'Unknown provider' error related to a provider I created for fetching template URLs. This provider is injected into a config function that is ...

Is there a way to automatically generate and allocate an identifier to an input field?

I've written the code below, but I'm having trouble figuring out if it's accurate. Specifically, I can't seem to access the text inputs that have been created by their respective id attributes. for (i=0;i<t;i++) { div.innerHTML=div. ...

When access to Ajax .responseText in an alert it can be displayed, however it cannot be stored in a variable or

var response_var=""; // Added for debugging purposes ajax.onreadystatechange = function() { if (ajax.readyState == 4 & ajax.status == 200) { response_var = ajax.responseText; alert(ajax.responseText); // This alerts properly (some text ...

Choose the element before and add a style effect with CSS

I'm trying to create a layout with 3 <div> elements in one horizontal line, each with a width of 33.33%. When hovering over one div, I want its width to expand to 50% while the other two shrink to 25%. <div id="A"></div> <div id= ...

What is the best way to retrieve data from Firebase and then navigate to a different page?

I am facing an issue with my app where I have a function that retrieves data from Firebase. However, after the completion of this Firebase function, I need to redirect it to another page. The problem is that when I press the button, the redirection happe ...

Issue encountered while attempting to start npm: Error code from NPM

I keep encountering the npm ENOENT error every time I attempt to execute npm start. I am unsure of what steps to take in order to resolve this issue. I have made efforts to adjust folder permissions. bryantcaruthers-> npm start npm ERR! code ENOENT npm ...

Redirecting to a separate component outside the current structure and transferring a callback function

How can I navigate from App.js, the default component, to a new component that is not within the hierarchy while passing a function? I have three components: Question for displaying questions, Upvote for upvoting, and Downvote for downvoting. Here is the ...

Discovering the identity of an item

Assume I have some JavaScript code like this: Foo = { alpha: { Name: "Alpha", Description: "Ipso Lorem" }, bravo: { Name: "Bravo", Description: "Nanu, Nanu" }, delta: { Name: "Fly with me", Desc ...

concerning a snippet of programming code

I'm new to coding and I'd like some help understanding this piece of code, particularly the red colored fonts. Which page value are they referring to? $(function() { $("#title").blur(function() { QuestionSuggestions(); }); }); funct ...

Showing hidden JavaScript elements in different parts of a webpage

Update: After making modifications to my JavaScript code, I am now encountering errors in the iPhone Debug Console. Disclaimer: As a newcomer to web development, I have limited expertise in JavaScript. Situation: My current project involves creating an e ...

Guide on integrating next-images with rewrite in next.config.js

I'm currently facing a dilemma with my next.config.js file. I've successfully added a proxy to my requests using rewrite, but now I want to incorporate next-images to load svg files as well. However, I'm unsure of how to combine both functio ...

The addition of a slash between the hashtag and the anchor name by Fullpage.js is causing conflicts with ng-include

My experience with using fullpage.js on a simple site alongside angular directives has been met with an issue. When including a .phtml file, the anchor functionality of fullpage.js stops working as it adds a slash before and after the anchor name. UPDATE ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

The system encountered an error due to the absence of a defined Google or a MissingKeyMapError from the

Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial. <div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}"> & ...

Adding default parameters in AngularJS Route-UI is a useful feature for setting up

Using angular UI-Router in my app, I've set up my base language as English. I have both English and Hebrew locals, and I want to avoid adding parameters to the URL if the language is English. For instance: Home English --> http://example.com/ Ho ...

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

Ben Kamens has developed a new feature in jQuery Menu Aim where the sub menu will not reappear once it

While exploring Ben Kemens’ jquery-menu-aim, I came across a demonstration on codepen. The code on codepen allows smooth transition from the main menu to the sub menu, but if you move away completely, the submenu remains visible and doesn't disappe ...