用javascript编写函数队列 [英] writing a function queue in javascript

查看:48
本文介绍了用javascript编写函数队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,每分钟只能发出60个API调用.所以我想做的是,当一个函数调用到来时,我知道我不会被放置,将其添加到队列中,并在更方便的时间再次调用该函数.

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

在这里我如何解决它

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();
}

这对于没有参数的函数很好,但是如果 make_api_call()有参数怎么办

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));     
    }
};

但是,在这种情况下,将在将 make_api_call(data)推送到 function_queue 之前对其进行评估,并且 func 将不再保存函数导致 queue_call()错误.

In this case however, make_api_call(data) will be evaluated before it is pushed to function_queue and func will no longer hold a function causing queue_call() to error.

我该如何解决?

推荐答案

您可以使用 bind 将部分参数应用于函数:

You can partially apply arguments to a function with bind:

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

检查 MDN 以获取支持在旧的浏览器中.

Check MDN for support in old browsers.

这篇关于用javascript编写函数队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆