Leon P-S
Leon P-S

Reputation: 46

Google Firestore promises

I am currently trying to work out how to do basic queries with Firestore an NodeJS. I am getting the error "Expected catch() or return". I was hoping someone could explain why this is happening?

I am using express router to handle routes.

Method 1. ESLint error

userRouter.get("randomroutename", (req, res) => {

    const uid = req.params.uid;
    console.log("User: " + uid);

    let collectionRef = db.collection('col');
    collectionRef.add({foo: 'bar'}).then(documentReference => {
        console.log(`Added document with name: ${documentReference.id}`);
        res.status(200).send('SUCCESS');
    });
});

After looking around and trying out a few things this appears to work, however I am really confused as to why the return is needed. It doesn't really make sense to me why I need to return a promise when surely the function 'add' is returning the promise which I can access .then from.

Method 2. No error

userRouter.get("randomroutename", (req, res) => {

    const uid = req.params.uid;
    console.log("User: " + uid);

    let collectionRef = db.collection('col');
    return collectionRef.add({foo: 'bar'}).then(documentReference => {
        console.log(`Added document with name: ${documentReference.id}`);
        return res.status(200).send('SUCCESS');
    });
});

As per the docs (https://googleapis.dev/nodejs/firestore/latest/CollectionReference.html), I believe method 1 should work.

Thanks for any help! (Very sorry if this is blindingly obvious I just can't get my head around it...)

Upvotes: 0

Views: 125

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

The message is saying "Expected catch() or return". Note that you have two options here. It would be appropriate to use return if you want to pass responsibility of the promise to the caller, but that's not what you want to do. What you should do instead is catch any potential errors captured by the promise returned by then, and deal with them appropriately:

collectionRef.add({foo: 'bar'}).then(documentReference => {
    console.log(`Added document with name: ${documentReference.id}`);
    res.status(200).send('SUCCESS');
}).catch(err => {
    res.status(500);
})

With that, if there was an error getting adding the document for any reason, it will generate a 500 response to the client.

None of this is unique to Firestore. This is just best practices in dealing with promises that ESLint is trying to get you to do.

Upvotes: 2

Related Questions