Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate.

The code snippet I am working with looks something like this:

const myObj = {};

function sendMessage(requestId, data) {
  kafkaProducer("requestTopic", {requestId, ...data});
  
  return new Promise(resolve => {
    // The challenge lies here
    const dataINeed = myObj[requestId];
    // This object is intended to be temporary only
    delete myObj[requestId];

    resolve(dataINeed);
  })
}

kafkaConsumer("callbackTopic", (response) => {
  myObj[response.requestId] = response.data;
}

I understand that the current code does not function as expected and this is the issue at hand. My goal is to resolve() the Promise only when the consumer actually generates the object, or on timeout.

Attaching the Promise to the consumer directly is not a viable option, as simultaneous requests necessitate their own distinct data rather than the data from the first response.

An alternative approach could involve creating a new consumer with a unique topic for each request. Upon consumption, the consumer would be terminated and the topic deleted in order to prevent overloading the kafka cluster with excessive ghost topics and partitions. However, it remains uncertain if this solution is advisable.

What prompts this necessity?

This functionality aims to replace traditional database requests by implementing a Database as a Service model while maintaining a structure akin to what APIs typically utilize (such as mongoose).

Answer №1

Keep a record of the resolve functions in your map instead of storing the result objects directly:

const messageObj = {};

function sendRequest(id, data) {
  return new Promise(resolve => {
    messageObj[id] = resolve;
    kafka.sendMessage(topic, { id, ...data });
  })
}

kafka.receiveMessage(callbackTopic, ({ id, data }) => {
  const resolveFunc = messageObj[id];
  if (!resolveFunc) throw new Error(`Received response for ${id} but the request does not exist`);
  delete messageObj[id];
  resolveFunc(data);
});

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

Determine the number of elements located inside a designated slot

Take a look at this Vue component code: <template> <!-- Carousel --> <div class="carousel-container"> <div ref="carousel" class="carousel> <slot></slot> </div> </div&g ...

What is the process for implementing optional chaining on a JSON object?

I'm currently facing an issue where I need to compare a value within a JSON object with a variable. if (resp.userdetails.name == username) { // do something } The challenge arises when not all resp objects contain the userdetails property, resulting ...

Utilizing RxJS finalize in Angular to control the frequency of user clicks

Can someone provide guidance on using rxjs finalized in angular to prevent users from clicking the save button multiple times and sending multiple requests? When a button click triggers a call in our form, some users still tend to double-click, leading to ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

What is the method for sending one URL as a parameter within another URL?

When I try to access the route /new/:url with a request like /new/https://www.google.com, the response is Cannot GET /new/https://www.google.com. What I actually want to receive is the string https://www.google.com. I came across an answer on URL compone ...

Tips for retrieving data from a database with just one key press

There is a text field that triggers a JavaScript function when a key is pressed. <input type="text" class="text" id="txt_sh_vid" onKeyPress="vhc_record()" maxlength="4"> The function takes the input from the text field and searches for a result in t ...

"Effortlessly transform a JSON string into a JSON Object with JavaScript - here's how

When I serialize my object using the ASP.net JavaScriptSerializer class and return it to the client side, how can I deserialize the string in JavaScript? ...

Is there a way to get this reducer function to work within a TypeScript class?

For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly: export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const s ...

What is the best way to create a loop using JSON information?

Seeking assistance to create a loop using JSON data to display the title, link, and description of advertisements in HTML format. Provided is a JSON template with two ads, but my actual JSON contains 10-20 IDs. What am I overlooking in the code below? Sto ...

Mobile devices are unable to properly implement the Jquery show/hide feature

Currently, I am working on a small Russian project and facing some challenges with the mobile version of my website: php8098.github.io/breakfast. The issue lies within the first slider where the play button should trigger a modal window to open. I urgentl ...

Triggering a keyboard *ENTER* event on an Input in Javascript/React by clicking a button is a common query among developers

I am facing a challenge with an Input element that only displays results when I press Enter on the keyboard. The element is part of a third-party extension, so my control over it is limited. My goal is to trigger the ENTER event for the Input when a button ...

streaming audio data from a MongoDB database to an HTML audio element

As part of my current project, I am delving into the realm of creating an audio player. The concept of database storage for files is relatively new to me, as my previous experience has mainly involved storing strings. Up to this point, here's what I ...

Customize the position of the Datetimepicker

Is there a way to customize the position of the datetimepicker, ensuring that it stays within the visual boundaries without getting cut off? I need help with this. ...

transferring double quotation marks and square brackets through a parameter

I have an angularjs (1.x) scope set up as follows: $scope.report = { resource: '/public/emplyACH', params: { "employeeId": [78] } }; When I try to access it using console.log (console.log(scope.parms)) I see the output as ...

Building an HTML form to generate an array of objects by collecting form data

Hey there, I'm working on an HTML form in React that utilizes form action and FormData. However, when I extract the formData using my method, it shows a structure like this: https://i.stack.imgur.com/nzgLX.png My goal is to have an array of objects ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolog ...

What is the best way to transfer information between two components in React.js by simply clicking a button?

One of the challenges I am currently facing involves rendering data from the Pokemon API in a table. Within this table, there is a button that allows users to select specific data when pressed. My goal is to send this selected data from the table component ...

What could be causing the lack of value appearing after I clicked the button?

Setting the value for the array of images as an empty string does not return the expected result. When I move one of the 4 images and click the button, I anticipate a new array with the information of one of the four images including src, x, and y coordina ...

Having trouble getting jQuery .click to trigger on a dynamically loaded button?

I'm having some trouble with my code. I have a list that loads dynamically with a button inside, and although I have set up jQuery to handle the click event, nothing is happening. Here's a snippet of the code: HTML: <ul id="cart"> ...