Google Cloud函数:functions.https.oncall返回null,但该值在日志中正确显示

发布于 2025-01-23 12:34:00 字数 1871 浏览 0 评论 0原文

我正在通过Axios async-wait调用第三方API,并通过Google Cloud函数将结果返回到扑动应用程序。我被迫使用functions.https.oncall,因为据我所知,Flutter无法调用onRequest函数。

该结果在console.log中正确显示在云功能的日志中,但是当flutter应用程序调用该函数时,它始终接收null。为什么?

getSmsBalance: functions.https.onCall(async (data, context) => {
    const business_id = data.business_id;
    const collectionRef = db.collection("buser_sms");
    const snapshot = await collectionRef.where("id", "==", business_id).get();
    if (snapshot.empty) {
        console.log("No matching documents - getSMSBalance .");
        let response = {
            status: false,
        };
        return JSON.stringify(response);
    }
    snapshot.forEach((doc) => {
        if (
            doc.data().enableReservationSms == true ||
            doc.data().enableAutoReminder == true ||
            doc.data().enableReminderSms == true
        ) {
            // get balance
            (async () => {
                const balance = await getBalance(
                    doc.data().senderId,
                    doc.data().username,
                    doc.data().password
                )
                    .then((result) => {
                        let response = {
                            status: true,
                            data: result,
                        };
                        console.log("balance is " + result);
                        return JSON.stringify(response);
                    })
                    .catch((err) => {
                        console.error(`Error - getSmsBalance - ${err}`);
                        let response = {
                            status: false,
                        };
                        return JSON.stringify(response);
                    });
            })();
        }
    });
}),

I am calling a third-party API via Axios async-await, and returning the result to a flutter application via a google cloud function. I am forced to use functions.https.onCall because flutter can't call onRequest functions as far as I know.

The result is shown correctly in console.log in the logs of the cloud function but when the flutter app calls the function, it's always receiving null. Why?

getSmsBalance: functions.https.onCall(async (data, context) => {
    const business_id = data.business_id;
    const collectionRef = db.collection("buser_sms");
    const snapshot = await collectionRef.where("id", "==", business_id).get();
    if (snapshot.empty) {
        console.log("No matching documents - getSMSBalance .");
        let response = {
            status: false,
        };
        return JSON.stringify(response);
    }
    snapshot.forEach((doc) => {
        if (
            doc.data().enableReservationSms == true ||
            doc.data().enableAutoReminder == true ||
            doc.data().enableReminderSms == true
        ) {
            // get balance
            (async () => {
                const balance = await getBalance(
                    doc.data().senderId,
                    doc.data().username,
                    doc.data().password
                )
                    .then((result) => {
                        let response = {
                            status: true,
                            data: result,
                        };
                        console.log("balance is " + result);
                        return JSON.stringify(response);
                    })
                    .catch((err) => {
                        console.error(`Error - getSmsBalance - ${err}`);
                        let response = {
                            status: false,
                        };
                        return JSON.stringify(response);
                    });
            })();
        }
    });
}),

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够钟 2025-01-30 12:34:00

您的代码有几个问题:

  1. 您在array.foreach内使用异步/等待语法,由于其内在的设计而不允许等待。如果要在循环迭代中使用异步/等待,则需要使用array.map例如。但是在大多数情况下,您不应在循环中使用异步/等待,因为它删除了异步代码执行的优势(每次迭代仅在上一个之后触发)。
  2. 除了快照。 返回 s 然后catch回调仅分配值然后。

因此,总而言之,您需要使用以下内容:

  return Promise.all(
    snapshot.map((doc) => {
      return getBalance(
        doc.data().senderId,
        doc.data().username,
        doc.data().password
      )
        .then((result) => {
          let response = {
            status: true,
            data: result,
          };
          console.log('balance is ' + result);
          return JSON.stringify(response);
        })
        .catch((err) => {
          console.error(`Error - getSmsBalance - ${err}`);
          let response = {
            status: false,
          };
          return JSON.stringify(response);
        });
    })
  );

请注意,我提供的代码剪切,而无需考虑您实际需要哪种格式作为输出。拥有响应 s的数组可能不是您需要的。但是您应该能够将该代码调整到最终所需的内容中。

There are several issues with your code:

  1. You are using async/await syntax inside an Array.forEach which does not allow to await because of its intrinsic design. If you want to use async/await within the loop iterations, you need to use Array.map for example. But in most cases, you shouldn't use async/await inside a loop because it removes the advantages of asynchronous code execution (each iteration is only triggered after the previous one).
  2. You don't return anything from your function, except in the case of snapshot.empty. The returns in the then and catch callbacks only assign the values to the variable balance which isn't used afterwards.

So in conclusion, you need to use something like:

  return Promise.all(
    snapshot.map((doc) => {
      return getBalance(
        doc.data().senderId,
        doc.data().username,
        doc.data().password
      )
        .then((result) => {
          let response = {
            status: true,
            data: result,
          };
          console.log('balance is ' + result);
          return JSON.stringify(response);
        })
        .catch((err) => {
          console.error(`Error - getSmsBalance - ${err}`);
          let response = {
            status: false,
          };
          return JSON.stringify(response);
        });
    })
  );

Note that I'm providing that code snipped without any consideration for what format you actually need as the output. Having an array of responses may not be what you need. But you should be able to adapt that code to what you need in the end.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文