"ESLint no-loop-func rule"在回调中需要循环变量时该怎么做

Lau*_*nce 4 javascript node.js ecmascript-6 eslint

我工作的公司要求我们遵循no-loop-func ES-lint规则.我处于回调中需要循环变量的情况.

下面是一个例子:

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);
}
Run Code Online (Sandbox Code Playgroud)

如何重构代码以便满足规则?

geo*_*org 6

只是不要使用循环.迭代器方法要好得多.

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

callback(null);
Run Code Online (Sandbox Code Playgroud)

要在完成所有操作后调用回调,您将需要以下内容:

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);
Run Code Online (Sandbox Code Playgroud)

  • @Laurence`var itemsLeft = uniqueIdentifiers.length;`then then if(--itemsLeft === 0){callback(null); 在回调函数中. (2认同)