【问题标题】:Declare var inside if statment and use it in the same if statement condtion在 if 语句中声明 var 并在相同的 if 语句条件中使用它
【发布时间】:2018-03-15 04:06:00
【问题描述】:

使用 nodejs,我从 api 获取数据。该 api 有限制率,所以我试图做一些从标头中获得限制的东西,比较最大和当前请求,如果它们相等,那么不要在一段时间内发送请求,你明白了。

我在考虑if 语句,但条件中的变量是在 if 语句本身内部的请求中声明的,例如:

if (curr > max - 2){
res.send("limit reached");
return;
}
else{
//use request module to get headers from the api and split header to get 
//max and current count of request then declare them to curr and max
//so when someone else call the same request it compare the old vars
// if the statement is false it do the call and get the new vars
//if it is true it make a delay before next request
}

我知道这很愚蠢,我什至吸收了基本逻辑,我不知道.. 如果有更好的方法可以有人指出它。谢谢

【问题讨论】:

    标签: node.js variables if-statement scope


    【解决方案1】:

    保持直截了当,在您的路线中全局声明变量curr(即在您的所有请求中)。在您的请求中每次成功的 api 调用之后更新(增量)curr。在每次 api 调用之前检查您的curr,如果超过限制则发送错误,否则继续您的调用。

    关键是nodejs中的全局变量会在你当前路由的整个生命周期中持续存在。

    假设您使用的是快递服务器。 但是,如果你想限制你的用户在整个应用程序中进行 api 调用,那么更喜欢使用 locals(app.locals)

    【讨论】:

    • 我在请求函数内的响应标头中获取速率限制
    • 在收到限制的地方更新全局变量或 app.locals.var
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多