Why does this vow continue to linger unresolved?

I've been experimenting with a code that involves adding promises to a queue for processing in a non-blocking manner. One code snippet behaves as anticipated while the other doesn't, leaving me puzzled.

Problematic Code:

const axios = require('axios');
const promiseQueue = require('promise-queue');

let currentQueueSize = 0;
const maxQueueSize = 5;

// eslint-disable-next-line new-cap
const queue = new promiseQueue(maxQueueSize, maxQueueSize);

const requestData = () => {
  currentQueueSize++;
  queue
    .add(() => axios.get('https://catfact.ninja/fact'))
    .then(result => {
      console.log(result.data);
    })
    .catch(e => {
      console.log(e);
    })
    .finally(() => {
      currentQueueSize--;
    });
};

const run = async () => {
  while (true) {
    if (currentQueueSize <= maxQueueSize) {
      console.log('current queue size ', currentQueueSize);
      requestData();
    }
  }
};

run();

I was under the impression that this code would add items to the queue, decrease the queue size upon resolution, and allow for more additions. However, the then block within the requestData function is never executed.

In contrast, when I modify the run code as follows:

const run = async () => {
  while (true) {
    if (currentQueueSize <= maxQueueSize) {
      console.log('current queue size ', currentQueueSize);
      ingestData();
    } else {
      await new Promise((resolve, _reject) => {
        const waiter = () =>
          setTimeout(() => {
            if (currentQueueSize <= maxQueueSize) {
              console.log(`Queue size ${currentQueueSize} now under  max queue size of ${maxQueueSize}, resuming...`);
              resolve(true);
            } else {
              console.log(`Waiting for queue size to reduce, current queue size ${currentQueueSize}`);
              waiter();
            }
          }, 1000);
        waiter();
      });
    }
  }
};

The execution of then, catch, and finally is as expected, allowing continuous additions to the queue as promises are resolved. What distinguishes the dysfunctional first code from the functional second one?

Answer №1

while (true) creates an endless loop without any opportunity for suspension due to the absence of an await. As a result, the entire application is being blocked, hindering the resolution of promises and the execution of their handlers.

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

Submenu animation that "bursts onto the scene"

I'm facing an issue with my menu that has sub-items inside it. To achieve the animation effect I desire, I need to extract the width, height, and first-child's height of the sub-menu. While my animation is working most times, there are instances ...

The Vue.js v-on:mouseover function is not functioning properly in displaying the menu

When I hover over a LI tag, I want to display a menu. I have successfully implemented it using a simple variable with the following code: @mouseover="hoverFormsControls=true" @mouseleave="hoverFormsControls=false" However, when I attempted to use an arr ...

How can you make an Angular directive activate only after the scope function in an ng-click handler has been executed?

Scenario I am relatively new to Angular and facing a specific challenge. The goal is to make a directive change the color and add an image to a button. However, I am struggling to get the first if condition to work in my Angular Directive. Issue The ob ...

Is it possible to move a directive within a limited parent element?

Is there a way to limit the movement of an angular.js drag directive within the confines of its parent element? You can see the problem I'm facing in this jsbin: http://jsbin.com/maxife/3/edit?html,css,js,output ...

My browser isn't triggering the jQuery change event, although it does work in jsfiddle

Whenever a textbox is changed, I want a specific function to be executed automatically. The code snippet below demonstrates my approach: var div = document.getElementById("tree"); var input = document.createElement('input'); input.id = 123; i ...

Expo: A guide on integrating expo code into an existing Android project

I'm looking to enhance my Android app (which is built in standard Java) by allowing users to create their own 3D models. To achieve this, I want to incorporate a 3D viewer within the app so that users can view and interact with their creations. My pl ...

Retrieve the concealed method's name within the immediately invoked function expression (IIFE

This Meteor sever code has a private method called printFuncName within an IIFE. However, when this method is invoked from a public method, it results in the following error: TypeError: Cannot read property 'name' of null I am curious to unde ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

Limitations of GitHub's rate limiting are causing a delay in retrieving user commit history

I have developed a code snippet to retrieve the user's GitHub "streak" data, indicating how many consecutive days they have made commits. However, the current implementation uses recursion to send multiple requests to the GitHub API, causing rate-limi ...

implementing secure authentication in nodejs with an api

I am currently working on a project that requires authentication through an external application's API. This API returns a response status (either success or failure) along with an access token. What I need is a straightforward authentication process ...

The component briefly displays the previous state before updating in the Material-UI Alert component

Whenever there is an error from an API while a user is registering, an alert is displayed on the form page. To handle this, an Alert component was created: <Snackbar open={open} autoHideDuration={9000} onClose={() => { setOpen(f ...

Does npm-check-updates have the ability to lock specific dependencies during the execution of ncu -ua command?

Utilizing npm-check-updates, we are managing updates for our dependencies listed in the package.json. We are encountering challenges due to having numerous small projects that require fixed versions of specific dependencies. As a module writer, we prefer ...

Issue occurred while proxying to the blog subdomain from a Node.js application

I currently have a NodeJS application running on Heroku, accessible at www.example.com. Additionally, I have a WordPress blog set up on a subdomain - blog.example.com. To handle routing, I've configured a route in Express: (utilizing express-http-pr ...

The JQuery File-Upload plugin remains inactive even after a file has been chosen

I am currently working on integrating the JQuery File-Upload plugin (). The issue I'm facing is that it doesn't respond when a file is selected. Here are some potential problems to consider: No errors appear in the Chrome console. Selecting a ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Why doesn't the div click event trigger when the mouse hovers over an iframe?

My dilemma involves a div element with a click event. When the div is positioned over an iframe area (closer to the user than the iframe), the click event fails to trigger. However, if the div is located elsewhere and not above the iframe, the click event ...

User authentication in MEAN Stack using passport-local and $routeProvider for routing

When it comes to logging users into my application, I am utilizing passport-local. The login process involves a function called in my AngularJS controller: $http.post('/login', $scope.user).then(function (response){ if(response.data.success) ...

Leveraging react-query with next-mdx-remote MDX Components?

I have been using next-mdx-remote in my next.js project. One of the components I've passed to it makes API calls using axios, which has been working well. However, I now want to switch to using react-query. When implementing this change, I encountered ...

Is there a way to obtain the specific guild ID from the ready event?

I am currently working on making this bot function across multiple servers, and I need to retrieve a specific guild ID similar to using message.guild.id. However, since there is no message defined or declared, I am unsure of how to achieve this. Any sugges ...

Using props in the v-bind:src directive with Vue - a comprehensive guide!

I have a Vue application with a Block component that needs to display an image. The Block component is used multiple times in the App component, each time passing a value to determine which image src to choose from an array. When I try to print {{ this.Im ...