如何让 Firestore 交易返回承诺?

2023-12-23

两天前我问了一个问题,得到的答复是“你的方法必须返回一个 Promise(或一个 Observable)”。

我已将代码更改为与“中的示例完全相同”https://firebase.google.com/docs/firestore/manage-data/transactions https://firebase.google.com/docs/firestore/manage-data/transactions“但问题是它将结果作为控制台日志传递,但我需要等待写入完成才能得到结果。

  orderIndex() {
    let db = this.firebase.firestore();
    var sfDocRef = db.collection("cities").doc("SF");
    db.runTransaction(function (transaction) {
      return transaction.get(sfDocRef).then(function (sfDoc) {
        if (!sfDoc.exists) {
          throw "Document does not exist!";
        }

        var newPopulation = sfDoc.data().population + 1;
        if (newPopulation <= 1000000) {
          transaction.update(sfDocRef, { population: newPopulation });
          return newPopulation;
        } else {
          return Promise.reject("Sorry! Population is too big.");
        }
      });
    }).then(function (newPopulation) {
      console.log("Population increased to ", newPopulation);
    }).catch(function (err) {
      // This will be an "population is too big" error.
      console.error(err);
    });
  }

我又花了两天时间试图得到回报。

我见过很多寻求帮助的问题并收到回复的代码建议。请帮忙,因为我是新手,并且在这个问题上花了四天多的时间。

顺便说一下,firebase.google 的代码有一个错误

return Promise.reject("Sorry! Population is too big.");

错误:“[ts] 类型 '(resolver: (resolve: (val: IWhenable) => void,reject: (reason: any) => void,notify: (prog...') 上不存在属性 'reject' ”。

我之前的问题是“如何更改函数中的承诺以阻止它在数据到达之前返回? https://stackoverflow.com/questions/49084295/how-do-i-alter-the-promises-in-my-function-to-stop-it-returning-before-the-data"


你的函数没有返回承诺并且也在then如果您没有返回任何值。

尝试这个:

  orderIndex() {
    let db = this.firebase.firestore();
    var sfDocRef = db.collection("cities").doc("SF");
    return db.runTransaction(function (transaction) { //Return here
      return transaction.get(sfDocRef).then(function (sfDoc) {
        if (!sfDoc.exists) {
          throw "Document does not exist!";
        }

        var newPopulation = sfDoc.data().population + 1;
        if (newPopulation <= 1000000) {
          transaction.update(sfDocRef, { population: newPopulation });
          return newPopulation;
        } else {
          return Promise.reject("Sorry! Population is too big.");
        }
      });
    }).then(function (newPopulation) {
      console.log("Population increased to ", newPopulation);
      return newPopulation; //Return the value
    }).catch(function (err) {
      // This will be an "population is too big" error.
      console.error(err);
    });
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让 Firestore 交易返回承诺? 的相关文章

随机推荐