如何避免在IF语句中嵌套承诺

时间:2019-04-29 11:00:24

标签: javascript firebase google-cloud-firestore

我知道我们不应该在函数中嵌套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
                }
            })

我不认为这是嵌套的,但是在部署时我仍然会收到警告。我应该如何重组此代码以避免嵌套警告?我知道那里有一些类似的答案,但是如果没有其他陈述,它们都没有

1 个答案:

答案 0 :(得分:1)

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

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