Create a composition of several debounce promises in JavaScript

I am looking for a way to efficiently manage multiple costly server calls by continuously invoking a function that accepts a key and returns a promise containing an object. This object is guaranteed to have the requested key along with additional values, including unrelated keys. The desired behavior of this function would be:

  • When first called, it should generate a promise.
  • Subsequent calls should accumulate keys to be sent to the server.
  • All calls will return the same promise until there has been 100ms of inactivity.
  • If no new calls are made within 100ms, all accumulated keys should be sent to the server for processing.
  • If a new call is made while waiting for a response from the server, it should initiate a fresh promise with its own set of pending keys.
  • Upon receiving the response from the server, the pending promise should be resolved.

Is there any npm package available that can assist with implementing this functionality, or should I develop it from scratch?

Answer №1

My search for a way to consolidate server requests using a single promise in NPM didn't yield any clear results. However, I will share some mockup code that utilizes ES6 promises, which could potentially serve as a starting point for a solution in the absence of other ideas. Please note that this code is not guaranteed to work perfectly...

/*******  application code  ********/

function requestKeys(keyArray) {
    // Promise an object with values for keys in keyArray:
    // Use asynchronous code to fetch values for keys in keyArray,
    // Return a promise for the parsed result object.
    // ...
}

const latency = 100; // Maximum delay between getting a key and sending a request

/********  generic code *********/

var getKey = ((requestKeys, latency) => {
    // Return a function that promises a key value object
    var promise = null;
    var resolve = null;
    var reject = null;
    var pendingKeys = null;

    var defer = () => {
        promise = new Promise((r, j) => {resolve = r; reject = j});
        pendingKeys = [];
    };

    var running = false;
    var timesUp = () => {
        resolve(requestKeys(pendingKeys));
        running = false;
    }
    var addKey = (key) => {
        if(!running) {
            defer();
            setTimeout(timesUp, latency);
            running = true;
        }
        pendingKeys.push(key);
        return promise;
    }
    return addKey;
})(requestKeys, latency);


/*******   test code   *******/

// Redefine requestKeys to provide an object with key strings as key values,
// Resolve the returned promise synchronously for testing:

function requestKeys(keyArray) {
    var keyObj = keyArray.reduce(((obj, v) => ((obj[v] = v), obj)), {});
    return new Promise((resolve, reject) => resolve(keyObj));
}

var log = obj => console.log(JSON.stringify(obj));

// Quickly retrieve two keys
getKey("holas").then(log);
getKey("buono").then(log);

// Wait and retrieve another key
setTimeout(function(){getKey('later').then(log)}, 500);

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

How to get the most out of the $scope variable?

Is it possible to assign a regular JavaScript variable the current value of an Angular $scope variable without having their values binded together? //$scope.var1 is set to a specific value, for example, 5 var v2 = $scope.var1; //$scope.var1 is then update ...

What happens when Google Polymer platform is used without defining _polyfilled?

My attempt at creating a simple example using Google Polymer's platform.js is running into an error message that says: Uncaught TypeError: Cannot read property '_polyfilled' of undefined This is what I'm attempting to achieve: <cur ...

What are the techniques for integrating PHP code into JavaScript/Ajax?

I am curious about how to integrate PHP code into JavaScript/Ajax. Here is the PHP code I am working with: if ($folder = opendir('data/Tasklist/')) { while (false !== ($file = readdir($folder))) { if ($file != '.' && $ ...

pictures in photo display

Please check out my codepen project: html code: <body> <div class="thumbnails"> <a href="#"><img src="http://s30.postimg.org/4yboplkxd/dotty.jpg" width="100" height="100"></a> <a href="#"><img src="http:// ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

Transferring information to an outside document using Ajax

My code works perfectly when I use this: ajax.open("post","a.php",true); However, the problem arises when I attempt to send data to an external file like this: ajax.open("post","http://www.example.com/a.php",true); Unfortunately, it doesn't work i ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

Accessing a webpage solely by logging in prevents unauthorized access

My login page currently redirects to a page named gallery.html upon successful login. However, I have noticed that entering /gallery.html in the URL also directly accesses the secure page without logging in. Can anyone suggest an effective way to impleme ...

Is there a way to transform JSON text into a JSON object?

Similar Question: How do I convert JSON to a JavaScript object? { "data": [ { "name": "JoongBum Lee", "id": "526210623" }, { "name": "\uc774\uc778\uaddc", ...

Access Images from Server using Front-End Technology

I have a collection of images stored in a server folder that I want to display on a div element using client-side code. Initially, I tried to achieve this with AJAX, but it returned raw data instead of the image URL. Despite my efforts to find a solution, ...

Utilizing URL Parameters in MEANJS

I'm currently testing my app on localhost:3000/#!/, and am encountering difficulties in retrieving URL parameters for use with Express. I have set up a new server routing file that includes the following: admin.server.routes.js 'use strict&apos ...

Ways to verify that window.open is being invoked from a React component

In my React component, I have a set of nested components, each with its own checkbox. The state hook rulesToDownload starts as an empty array and dynamically adds or removes IDs based on checkbox selection. Upon clicking the 'download' button, t ...

What is the syntax for accessing a nested object within the .find method?

Currently building an application in node.js. I am struggling with referencing the "email" element in the "userData" object within the Order model when using the find method. Any suggestions on how to properly refer to it? Order model: const orderSchema = ...

Tips for utilizing mermaid sections in quarto?

I'm facing an issue with embedding mermaid chunks in my Quarto HTML document. Unfortunately, I can't seem to get the chunks to run as I keep receiving the error message /bin/sh mermaid: command not found. An accompanying screenshot displays the p ...

MongoDB suggests

I'm currently developing an app that requires autocomplete functionality for search. I've started implementing it using regular expressions (regexp), but I'm unsure if this is the optimal approach. Each new character input in the search bar ...

To elevate your Vue.js development in 2021, enhance your project by installing sass-loader and node-s

Having trouble setting up SASS for Vue.js. Here's the setup: Node.js - Version 15.7.0 Vue.js - @vue/cli Version 4.5.11 Encountering this error in the console when running the command: npm install -D sass-loader node-sass npm ERR! code ERESOLVE npm ERR ...

text box with an immobile header

As the browser window size decreases, the layout changes. However, when scrolling down, the search text box moves up and is no longer visible due to its lack of fixation. How can I make the search text box stay fixed as I scroll down? I tried implementing ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

How can Angular JS detect the names of the CSS files being used in an HTML page?

I am in the process of developing a brand new widget where we are incorporating a unique feature that displays the number of CSS files included within an HTML page. Our team requires the count and names of all CSS files utilized on the webpage. While I a ...

Monitoring inbound and outbound traffic in express middleware

I am in the process of incorporating a logger into my Express application. This logger needs to record both requests and responses (including status codes and body content) for each request made. My initial approach involves creating a middleware function ...