javascript - 如何在 JavaScript 中模拟数据库限制?

标签 javascript asynchronous callback

不久前,我在带回家的测试中遇到了一道代码问题。如下:

Database Throttling

You are given an array userInfo of user data and a function updateDB that takes a single user data argument. updateDB makes an asynchronous call that parses the user data and inserts the parsed data into a database. The database throttles requests so to make sure all user data is added to the database we need a function addAllUserData that calls updateDB on each entry in userInfo making sure never to exceed 7 calls per second to prevent being throttled.

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

正如你从我的尝试中看到的,我很难集中精力完成这项练习。任何人都可以注入(inject)关于异步调用的限制是什么意思吗?

提前致谢!

最佳答案

// 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*/ } 
}

关于javascript - 如何在 JavaScript 中模拟数据库限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41553359/

相关文章:

Javascript - 根据函数结果更改图像的不透明度

c# - 并行启动多个异步任务的最佳方式?

javascript - 捕获Javascript中的图片特定错误

java - 如何监听异步服务器端Java Controller ?

java - 在可完成的 future 之内/之后抛出异常

c++ - KeyboardProc 回调函数没有被调用?

javascript - 使用 CasperJS 迭代参数化 URL 时仅执行最后一次迭代

java - 在我的示例中,这个异步调用是如何工作的

javascript - DOM 操作的最佳工具?

javascript - jQuery UI 可拖动 : Mouse moves faster than draggable div