2017-01-09 22 views
0

前段时间我在回家测试中遇到了一个代码问题。这是如下:如何模拟JavaScript中的数据库调节?

数据库节流

您正在给定的用户数据的阵列USERINFO和功能updatedb的采用单个用户数据的参数。 updateDB进行异步调用,解析用户数据并将解析的数据插入到数据库中。该数据库节流请求,以便确保所有的用户数据被添加到数据库中,我们需要一个函数addAllUserData是在USERINFO每个条目确保永远不会调用updatedb的超过每秒7个呼叫防止被节流。

var userInfo = [{'name':'antonio', 'username':'antonio_pavicevac_ortiz'}], dataBase = []; 

function updateDB(singleUserDataArgument, callback){ 
    dataBase.push(callback(singleUserDataArgument)); 
} 

function addAllUserInfo(data) { 
    var eachUserData; 
    setInterval(function(){ 
     eachUserData = data.map(data) 
    }, 7000); 
} 

你可以通过我的努力,我有一个很难包装我的头围绕这个练习看看。任何人都可以注入对异步调用的限制意味着什么?

在此先感谢!

+2

我不认为从抽象的角度来看,节流与异步有什么关系。数据库不会接受来自客户端的每秒多于7次的呼叫,否则它可能会在每秒七次的限制内丢弃额外的请求。 因此,您可以跟踪您每秒拨打多少电话或拨打七个电话,等待一秒钟,再拨七个电话等。 – mrogers

+0

感谢Mrogers!那么在这个例子中,他们基本上是通过期望你以某种方式注入setInterval来推断节流? –

+1

我会假设他们会标记一个答案,可以每秒发送超过七个请求到数据库。所以是的,你可以用setInterval或者其他一些JS函数来完成。 – mrogers

回答

2
// contains times at which requests were made 
var callTimes = []; 

function doThrottle(){ 
    // get the current time 
    var time - new Date().getTime(); 

    // filter callTimes to only include requests this second 
    callTimes = callTimes.filter(function(t){ 
    return t > time-1000; 
    }); 

    // if there were more than 7 calls this second, do not make another one 
    if(callTimes.length > 7) return true; 

    else{ 
    // safe, do not throttle 
    callTimes.push(time); 
    return false; 
    } 
} 

// use like this 
function makeRequest(){ 
    if(doThrottle()){ /* too many requests, throttle */ } 
    else{ /* it's safe, make the ajax call*/ } 
}