create a queue for sending to api in javascript

To create a queue for sending requests to an API in JavaScript, you can use an array as the queue and the fetch API for sending the requests asynchronously.

First, you can define an empty array to use as your queue:

index.tsx
const requestQueue = [];
25 chars
2 lines

Next, you can create a function to add requests to the queue. This function can take the url of the API endpoint and an optional data object to send in the request:

index.tsx
function addToQueue(url, data = {}) {
  requestQueue.push({
    url,
    data
  });
}
86 chars
7 lines

This function adds an object to the requestQueue array, which contains the url and data for the API request.

To send the requests in the queue, you can create another function that uses fetch to send the requests asynchronously. This function can pop requests off the queue one at a time until there are no more requests left:

index.tsx
async function sendRequests() {
  while (requestQueue.length > 0) {
    const { url, data } = requestQueue.shift();
    const response = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(data)
    });
    console.log(response.json());
  }
}
259 chars
11 lines

This function uses a while loop to continually pop requests off the requestQueue array until it is empty. For each request, it sends a POST request to the url with the data as the body of the request. It then logs the JSON response from the API.

You can then call addToQueue to add requests to the queue and call sendRequests to send the requests in the queue:

index.tsx
addToQueue('https://example.com/api', { name: 'John', age: 30 });
addToQueue('https://example.com/api', { name: 'Jane', age: 25 });
sendRequests();
148 chars
4 lines

This code adds two requests to the queue and then sends them using sendRequests. The requests are sent asynchronously, so the order of the responses may not match the order of the requests in the queue.

gistlibby LogSnag