gpt4 book ai didi

javascript - 如何避免在 IF 语句中嵌套 promise

转载 作者:行者123 更新时间:2023-11-30 19:36:29 26 4
gpt4 key购买 nike

我知道我们不应该在函数中嵌套 promise ,而且我的所有函数根本没有任何嵌套,但是我不知道如何避免在我的一个函数的 if-else 语句中嵌套 promise 。

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

我不认为这是嵌套,但我在部署时仍然收到警告。我应该如何重组此代码以避免嵌套警告?我知道那里有一些类似的答案,但没有一个有 if else 语句

最佳答案

您可以抛出错误并捕获它,如下所示:

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

关于javascript - 如何避免在 IF 语句中嵌套 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55901953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com