[英]Call function only once after a map()
我在Node.js上遇到问题,当item.IS_RACING === 1
时,只需要调用一次函数
看
_.map(recordsets, function(items) {
return _.map(items, function(item) {
if (item.IS_RACING === 1) {
_this.getRacing();
}
});
});
我有那个_this.getRacing();
每次条件为true
调用它,但是如果有20个项目的IS_RACING === 1
,那么函数_this.getRacing();
将被呼叫20次。 我需要类似的东西,一旦应用程序检测到第一个IS_RACING === 1
出现时,便触发_this.getRacing();
只有一次。
有什么建议吗?
正如Pointy
在评论中指出的(抱歉),您确实不想使用map()
来执行此操作。
从如何向其他开发人员解释问题的角度考虑问题。
如果任何记录集中有一个正在赛车的项目,我想调用
getRacing()
。
现在,编写代表您意图的代码。
var somethingIsRacing = _.some(recordsets, function(items) {
return _.some(items, function(item) {
return item.IS_RACING === 1;
});
});
if(somethingIsRacing) {
_this.getRacing();
}
该代码遵循称为命令查询分隔的原则,在该原则中,您首先使用一种功能编程风格来查询以查找所需的信息,然后使用命令式编程风格执行会产生副作用的动作。
标志变量通常可以解决问题:
var getRacingCalled = false;
_.map(recordsets, function(items) {
return _.map(items, function(item) {
if (item.IS_RACING === 1 && !getRacingCalled) {
_this.getRacing();
getRacingCalled = true;
}
});
});
尝试使用闭包操作:
var closure = (function() {
var fired = false;
return function (item) {
if (!fired && item.IS_RACING === 1) {
fired = true;
_this.getRacing();
}
};
})();
_.map(recordsets, function(items) {
return _.map(items, closure(item));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.