Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"ESLint no-loop-func rule" What to do when loop variables are required in a callback

The company where I work for requires us to follow the no-loop-func ES-lint rule. I am in a situation where a loop variable is required in a callback.

An example can be found bellow:

var itemsProcessed = 0;
for (var index = 0; index < uniqueIdentifiers.length; index++) {
  let uniqueIdentifier = uniqueIdentifiers[index];

  // ESLint: Don't make functions within a loop (no-loop-func)
  var removeFileReferenceCallback = function (removeReferenceError) {
    if (removeReferenceError !== null) {
      NotificationSystem.logReferenceNotRemoved(uniqueIdentifier, undefined);
    }

    // When all items are removed, use the callback
    if (++itemsProcessed === uniqueIdentifiers.length) {
      callback(null);
    }
  };

  // Remove the reference
  this.database.removeFileReference(uniqueIdentifier, removeFileReferenceCallback);
}

How can the code be refactored so that the rule can be met?

like image 701
Laurence Avatar asked Apr 29 '16 07:04

Laurence


1 Answers

Just don't use loops. Iterator methods are so much better.

uniqueIdentifiers.forEach(function(uid) {
    this.database.removeFileReference(uid, function (err) {
        if (err) {
            NotificationSystem.logReferenceNotRemoved(uid, undefined);
        }
    });
}, this);

callback(null);

To call a callback after everything has been completed, you're going to need something like this:

var db = self.database;

var promises = uniqueIdentifiers.map(function(uid) {
    return new Promise(function (res) {
        db.removeFileReference(uid, function (err) {
            if (err) {
                NotificationSystem.logReferenceNotRemoved(uid, undefined);
            }
            res();
        });
    });
});

Promise.all(promises).then(callback);
like image 95
georg Avatar answered Nov 14 '22 23:11

georg