Search code examples
javascriptnode.jsgoogle-cloud-firestorepromisees6-promise

Error: You must return a Promise in your transaction()-callback. at transaction.begin.then


This is my code snippet:

await firestore.runTransaction(t => {
        t.get(docRef)
            .then(docRef => {
                logger.info("entering transaction");
                if (!docRef.exists) {
                    t.create(docRef, new Data);
                    return Promise.resolve();
                } else {        
                    t.update(docRef, {aField: updateData});
                    return Promise.resolve();
                }
            })
            .catch(error => {
                return Promise.reject(error);
            });
    })

This gives me the following error:

Error: You must return a Promise in your transaction()-callback. at transaction.begin.then (/srv/node_modules/@google-cloud/firestore/build/src/index.js:496:32) at

It's my first time using firestore transaction syntax, and I know fairly about nodejs promise concepts and syntax. I mimiced the firestore transaction example here and wrote the above snippet.

After the error, I tried to change Promise.resolve() to Promise.resolve(0), but in vain.

I also tried to remove await and instead use .then, but it still gives me the same error.

Please shed some lights on it. Appreciate it. Thanks.


Solution

  • You need to basically return the Promise. Also, if t.create and t.update returns a promise as well, you can just return that. Don't do return Promise.resolve(), Which is wrong because it will resolve BEFORE actually inserting or creating.

    Assuming everything works fine you need to do:

    await firestore.runTransaction(t => {
      return t.get(docRef)
        .then(docRef => {
          logger.info("entering transaction");
          if (!docRef.exists) {
            return t.create(docRef, new Data);
          } else {
            return t.update(docRef, { aField: updateData });
          }
        })
        .catch(error => {
          return Promise.reject(error);
        });
    })