我得到了一个"避免嵌套承诺" (对于jslint)用于以下函数。如何在没有嵌套承诺的情况下写出来?
function deleteUIDsFromDBForKey(rootkey, users_uids) {
return retrieveUIDsFromDBForKey(rootkey)
.then(uids => {
let diff = uids.diff(users_uids)
let deletes = []
diff.forEach(key => {
deletes.push(firebase.database().ref(rootkey + "/" + key).remove())
})
return Promise.all(deletes)
.then(value => {
return diff
})
})
}
答案 0 :(得分:0)
在这种情况下,我认为jsLint只是指导你做错了更复杂的代码。有时,你从linter得到它,在这种情况下最好的选择是绕过特定代码或函数行或特定的linter规则的linter。
这是我能想到的最简单,最清晰的代码实现(应该是您的优先考虑):
function deleteUIDsFromDBForKey(rootkey, users_uids) {
return retrieveUIDsFromDBForKey(rootkey).then(uids => {
const diff = uids.diff(users_uids);
// wait for all deletes to be done, then return diff
return Promise.all(diff.map(key => {
return firebase.database().ref(rootkey + "/" + key).remove();
})).then(() => diff);
});
}
或者,使用Bluebird' .map()
,你可以这样做:
// using Bluebird's Promise.map()
function deleteUIDsFromDBForKey(rootkey, users_uids) {
return retrieveUIDsFromDBForKey(rootkey).then(uids => {
const diff = uids.diff(users_uids);
// wait for all deletes to be done, then return diff
return Promise.map(diff, key => {
return firebase.database().ref(rootkey + "/" + key).remove();
}).then(() => diff);
});
}
或者,使用async / await:
async function deleteUIDsFromDBForKey(rootkey, users_uids) {
const uids = await retrieveUIDsFromDBForKey(rootkey);
const diff = uids.diff(users_uids);
await Promise.all(diff.map(key => {
return firebase.database().ref(rootkey + "/" + key).remove();
}));
return diff;
}
我没有安装支持ES7的jsLint,但最后一个选项应该避免嵌套警告。前两个,可能不是,但试图避免这个警告只会使代码变得更糟,所以IMO,你应该只是禁用警告。