Guidelines for queuing method calls using Vue.js

Is there a way to invoke a method using a queue system? Imagine having a method that makes API calls and can only handle 3 calls at once. If more than 3 calls are made from a component, the remaining ones should wait until one call finishes before proceeding.

Just to clarify, this is not about looping API calls, but rather calling them based on user actions in a real project.

for (let i = 0; i < 9; i++) {
  doSomething(i)
}

doSomething(param){
//call api
}

The goal is to execute doSomething for values 0 - 9, but ensuring that only the first 3 calls trigger API requests while the rest will be queued and wait for an available slot.

Answer №1

Consider utilizing the power of Promises and async functions in your code implementation.

Here is a simple example to guide you:

for (let i = 0; i < 9; i++) {
  performTask(i)
}

async function performTask(param) {
  if (param < 3) {
    const result = await fetchData();
    console.log(result);
  } else {
    const result = await fetchData();
    console.log(result);
  }
}

async function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('data fetched successfully')
    }, 2000)
  })
}

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

Closures are like the "use" keyword in PHP or the capture list in C++, but they play a similar role in JavaScript and other transpiler languages

PHP has a useful feature with the use keyword, which allows for the usage of 'external' variables in closures. For example: $tax = 10; $totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use' return ($price * $quan ...

What is the process for including an optional ngModelGroup in Angular forms?

I'm encountering an issue with incorporating the optional ngModelGroup in angular forms. Although I am familiar with how to use ngModelGroup in angular forms, I am struggling to figure out a way to make it optional. I have attempted to pass false, nu ...

How can I include line breaks using HTML `<br>` tags in a textarea field that is filled with data from a MySQL

Within a modal, I am showcasing a log inside a read-only <textarea> field that contains data fetched from my MySQL database. Below this, there is a writable <textarea> field where users can input updates to the log, which are then added to the ...

applying attributes to an element

Can you tell me why the addClass method is adding the class 'foo' to both the div and p element in the code snippet below? $('<div/>').after('<p></p>').addClass('foo') .filter('p').attr ...

Avoid the default behavior when employing jQuery for Ajax requests

I am facing an issue with preventing the default action when submitting a form using ajax. It seems that my code is causing a page refresh and clearing the form without sending any data to the database. I tried including the php processing script link in t ...

Is it possible to utilize the inline/hardcoded type declared in the component.d.ts file for reuse

Is there a way to pass props selectively to the library component? The library has hardcoded multiple values in an inline type. If my code needs to automatically update with any new additions to the library-defined type, can I reuse those inline values r ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

Ways to use the v-if directive to render conditionally based on a property, even if the object may be undefined

Keep in mind that the parent variable is a firebase reference that has already been defined. Using it like this works fine: v-if="parent['key'] == foo" However, when trying to access a child element like this: v-if="parent['key'].ch ...

Forward to a SubDomain

Utilizing Yellowtree's GEOIP-Detect plugin, I attempted to implement a location-based redirection system for visitors. Unfortunately, I encountered issues with the code execution. The process initially involves extracting the user's IP address an ...

fetch the image data from the clipboard

Hey there! Is it possible to use JavaScript to retrieve an image from the system clipboard (Windows/Mac) and paste it into a website? ...

How to change a date object into a datestring using the TZ format in JavaScript

Here is the input: const date = "06/01/2018" const time = "06:25:00" The desired output format is a string like this: "2018-06-01T00:55:00.000Z". I attempted to create the Date object using const result = new Date(date + time); //outputs an obje ...

What is the difference in speed between drawing on a transparent canvas and determining if a point is transparent compared to determining if a point is within a complex polygon?

I'm curious if anyone has done research on adding event support to a game engine. Specifically, I am working on incorporating pixel-perfect hover over 2D object event support into my own game engine. I am exploring different ways of achieving this eff ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

Jest throws an error: require function is not defined

I've been struggling with an issue in Angular for the past 3 days. I'm using [email protected] and [email protected]. I even tried downgrading and testing with LTS versions of node and npm, but I keep encountering the same error. Here ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

Utilizing JavaScript to assign a CSS class to an <li> list item

I am working on a page that includes a menu feature: https://jsfiddle.net/dva4zo8t/ When a menu button is clicked, the color changes and I need to retain this color even after the page is reloaded: $('[id*="button"]').click(function() { $( ...

I encountered an issue while attempting to install dependencies listed in the package.json file using the npm install command

npm encountered an error with code 1 while trying to install a package at path C:\Users\HP\Desktop\workings\alx-files_manager\node_modules\sharp. The installation command failed due to issues with the sharp plugin and its ...

Is the object returned by the useParams hook maintained across renders?

The book that is displayed is based on the URL parameter obtained from the useParams hook. The selected book remains constant across renders unless there is a change in the value returned by the useParams hook. I am curious to find out if the object retur ...

Reverse lookup and deletion using Mongoose

Currently, I am attempting to perform a health check on the references within one of my collections. The goal is to verify if objects being referenced still exist, and if not, remove that particular _id from the array. Despite my efforts, I have not come ...

Choose information based on the prior choice made

Using the Material UI Stepper, I have a task that involves setting conditions based on the selection of checkboxes. In step one, there are two checkboxes - Individual and Bulk. In step two, there are also two checkboxes - First Screening and Second Screeni ...