user6935527
user6935527

Reputation:

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

Upvotes: 1

Views: 137

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83153

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

Upvotes: 1

Related Questions