如何避免在IF语句中嵌套承诺 [英] How to avoid nesting promises in IF statement
本文介绍了如何避免在IF语句中嵌套承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们不应该在函数中嵌套promise,而我的所有函数都没有任何嵌套,但是我无法弄清楚如何避免在函数之一的if-else语句中嵌套promise.
I know we should not nesting promises in functions and all my functions are without any nesting at all however I can't figure out how to avoid nesting promises in if-else statement in one of my function.
const staffRef = db.collection("staff").doc(uid)
return staffRef.get()
.then((doc) => {
if (doc.exists) {
return staffRef.delete()
.then(() => {
console.log("Employee ", uid, " profile has been deleted in staff collection")
return null
})
} else {
console.log("Employee ", uid, " had no dependencies")
return null
}
})
我不认为这是嵌套的,但是在部署时我仍然会收到警告.我应该如何重组此代码以避免嵌套警告?我知道那里有一些类似的答案,但是如果没有其他陈述,它们都没有
I don't think this is nesting but I still get warnings while deploying. How should I restructure this code to avoid nesting warning? I know there some similar answers out there but none of them have if else statement
推荐答案
您可以引发错误并捕获它,如下所示:
You can throw an error and catch it, as follows:
const staffRef = db.collection("staff").doc(uid)
return staffRef.get()
.then((doc) => {
if (doc.exists) {
return staffRef.delete();
} else {
console.log("Employee ", uid, " had no dependencies")
throw new Error("Employee " + uid + " had no dependencies");
}
})
.then(() => {
console.log("Employee ", uid, " profile has been deleted in staff collection");
return null;
})
.catch(error => {
console.log(error);
return null;
});
这篇关于如何避免在IF语句中嵌套承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文