简体   繁体   中英

Call function only once after a map()

I am having an issue on Nodejs, I need to call a function only once when item.IS_RACING === 1

look

    _.map(recordsets, function(items) {
      return _.map(items, function(item) {
        if (item.IS_RACING === 1) {
          _this.getRacing();
        }
      });
    });

I have that _this.getRacing(); which is being called everytime the conditional is true , but if there is 20 items with IS_RACING === 1 , so the function _this.getRacing(); is going to be call 20 times. I need something like, once the app detects when the first IS_RACING === 1 comes up, then fires _this.getRacing(); only once.

Any recommendation ?

As Pointy pointed out (sorry) in the comments, you really don't want to use map() to do this.

Think of the problem in terms of how you would explain it to another developer.

If any of the record sets has an item that is racing, I want to call getRacing() .

Now, write code that represents your intent.

var somethingIsRacing = _.some(recordsets, function(items) {
  return _.some(items, function(item) {
    return item.IS_RACING === 1;
  });
});
if(somethingIsRacing) {
  _this.getRacing();
}

This code follows a principle called Command-Query Separation, where you first query to find the information you need using a functional style of programming, then you perform actions that will have side-effects using an imperative programming style.

A flag variable usually does the trick:

var getRacingCalled = false;
_.map(recordsets, function(items) {
  return _.map(items, function(item) {
    if (item.IS_RACING === 1 && !getRacingCalled) {
      _this.getRacing();
      getRacingCalled = true;
    }
  });
});

Try to do it with a closure:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM