简体   繁体   中英

firebase cloud functions oncall returns null

wondering what's the weird error.

I am using the onCall method from firebase cloud functions, but when I read it from my app it returns null value. I am trying to return some test data but it doesn't seem to be working. Am i returning the data wrongly?

index.js


    exports.handleMassFollowAnalytics = functions.https.onCall((data, context) => {
      const brandArray = data.brandArray;
      const followed = data.followed;

      let done = 0;
      for (var i = 0; i < brandArray.length; i++) {
        let brand = brandArray[i];
        admin.database()
          .ref(`brands/${brand}/followers`)
          .transaction(function(post) {
              if (post !== null) {
                post--;
              }
              return post;
            },

            function(error, committed, snapshot) {
              done++;
              if (done === brandArray.length) {
                // returning result.
                return {
                  data: "testabc",
                };
              }
            }
          );
      }
    });


app.js

    const handleMassFollowAnalytics = firebase
      .functions()
      .httpsCallable("handleMassFollowAnalytics");
    handleMassFollowAnalytics({
      brandArray: array,
      followed: true,
    }).then((result) => {
      console.log("result: ", result) // returns null everytime
    });

Your function needs to return a promise that resolves with the data to send to the client. Right now, your function returns nothing. The return statement inside the transaction callback is not returning from the main function.

Also, the code is ignoring the promises returned by the transactions you're performing. The final promise returned from the function must resolves only after all the other promises resolve.

So, I used Doug's information and arrived at the following answer, for reference to anyone in future.

This seems to return correctly for me.

  1. Return individual promises
  2. Return final promise

index.js

    exports.handleMassFollowAnalytics = functions.https.onCall((data, context) => {
      const brandArray = data.brandArray;
      const followed = data.followed;

      var promises = [];
      for (var i = 0; i < brandArray.length; i++) {
        let brand = brandArray[i];
        promises.push(admin.database()
          .ref(`brands/${brand}/followers`)
          .transaction(function(post) {
              if (post !== null) {
                post--;
              }
              return post;
            });
        );
      }

      return Promise.all(promisess).then((result)=>{
          return {
              data: "testabc",
          }
      })
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM