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)
如何重构代码以便满足规则?
只是不要使用循环.迭代器方法要好得多.
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)
归档时间: |
|
查看次数: |
2313 次 |
最近记录: |