Ad

How To Avoid Nesting Promises In IF Statement

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

Ad

Answer

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;
        });
Ad
source: stackoverflow.com
Ad