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

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

这是我的代码片段:

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

这给了我以下错误:

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

第一次使用firestore事务语法,对nodejs的promise概念和语法比较了解。我模仿了 firestore 事务示例 here 并编写了上面的代码片段。

报错后,我尝试将Promise.resolve()改成Promise.resolve(0),但没有成功

我也尝试删除 await 并改为使用 .then,但它仍然给我同样的错误。

请阐明它。欣赏它。谢谢。

您基本上需要 return Promise。此外,如果 t.createt.update return 也是一个承诺,您可以 return 那个。不要做 return Promise.resolve(),这是错误的,因为它会在 之前 实际插入或创建。

假设一切正常,您需要做的是:

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

回顾这个例子,我意识到我在 return t.get() 中错过了 return,但这个错误并不明显,无法指出我的错误..