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

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

我工作的公司要求我们遵守 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);
}

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

只是不要使用循环。迭代器方法好多了。

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

callback(null);

要在一切完成后调用回调,您需要这样的东西:

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

我的所有 JavaScript 都使用 ESList,并且我遵守 no-loop-func 规则,如果不这样做,它会咬你一口。原因在这里得到了很好的解释:JavaScript closure inside loops – simple practical example.

我建议在重构方面的其他答案。

使用bind可以解决您的问题吗?

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

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

function removeFileReferenceCallback(removeReferenceError) {
    if (removeReferenceError !== null) {
        NotificationSystem.logReferenceNotRemoved(this, undefined);
    }

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

我也把我的对象转成数组,然后用forEach。