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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With