Writing a function queue in javascript

I have an object that can only place 60 API calls per minute. So, what I would like to do is when a function call comes in that I know, I will not be allowed to place it, add it to the queue and call the function again at a more convenient time.

This is how I decided to fix it

var API_caller = function(){ this.function_queue = []; }; API_caller.prototype.make_api_call = function(){ if(this.can_make_call()){ this.make_call(); } else { // If I cant place an API call then add // the function to the function queue this.function_queue.push(this.make_api_call); } }; API_caller.prototype.queue_call = function(){ // remove function from queue and call it var func = this.function_queue.shift(); func(); } 

This works fine for functions without parameters, but what if make_api_call() had a parameter

 API_caller.prototype.make_api_call = function(data){ if(this.can_make_call()){ this.make_call(); } else { // If I cant place an API call then add // the function to the function queue this.function_queue.push(this.make_api_call(data)); } }; 

In this case, however, make_api_call(data) will be evaluated before function_queue is clicked, and func will no longer contain the function that causes the queue_call() error.

How can I get around this?

0
source share
3 answers

You can partially apply arguments to a function using bind :

 this.function_queue.push(this.make_api_call.bind(this, data)); 

Mark MDN for support in older browsers.

+1
source

The queue entry must contain the function f and parameters as an array, p .

When you add to the queue, you do something like queue.push ([f, arguments]) , and when the time comes to make this call, it will be something like queue[0][0].apply (null, queue[0][1])

0
source

You can queue a special function containing your API call with an argument already bound:

 var that = this; this.function_queue.push(function() { that.make_api_call(data); )); 

Smoothing is required from this to that , because inside the anonymous function, this will not be bound to the same object as outside.

Note that this method is similar to eclanrs answer, but does not rely on the availability of the bind method.

0
source

Source: https://habr.com/ru/post/947420/


All Articles