【问题标题】:Querying firebase HTTPs function in a loop only invokes the last call multiple times在循环中查询firebase HTTPs函数只会多次调用最后一次调用
【发布时间】:2023-03-08 05:24:01
【问题描述】:

当用户登录我的应用程序时,我想将初始详细信息(如用户联系人列表)发送到后端以处理用户创建。由于这是一项漫长的工作,我想将其拆分为单独的 HTTPs 调用。

为简单起见,这里是应用端请求:

for (int i = 0; i < 3; ++i) {
    data.put("val", String.valueOf(i));
    firebaseFunctions.getHttpsCallable("sandbox").call(data)
        .addOnFailureListener(e -> Log.e("Error; " + e.getMessage()))
        .addOnSuccessListener(result -> Log.v("Success! Got " + result.getData()));
}

和 HTTPs 函数(在 Node.js 中):

exports.sandbox = functions.https.onCall((data, context) => {
    console.log("In, data.val is " + data.val);
});

如果我像这样通过firebase functions:shell shell 调用函数:

for (let i = 0; i < 3; ++i) {
    sandbox.post('').json({"data": {"val": "" + i}});
}

我得到了输出:

In, data.val is 0
In, data.val is 1
In, data.val is 2

但如果应用代码运行,Firebase 控制台会显示以下日志:

2018-05-16T10:09:02.080247334Z D sandbox: Function execution started
2018-05-16T10:09:02.080333313Z D sandbox: Billing account not configured. 
    External network is not accessible and quotas are severely limited. 
    Configure billing account to remove these restrictions
2018-05-16T10:09:03.051Z I sandbox: In, data.val is 2
2018-05-16T10:09:03.135023272Z D sandbox: Function execution took 1056 ms, finished with status code: 200
2018-05-16T10:09:04.073804790Z D sandbox: Function execution started
2018-05-16T10:09:04.073930247Z D sandbox: Billing account not configured. 
    External network is not accessible and quotas are severely limited. 
    Configure billing account to remove these restrictions
2018-05-16T10:09:04.236Z I sandbox: In, data.val is 2
2018-05-16T10:09:04.239244077Z D sandbox: Function execution took 166 ms, finished with status code: 200
2018-05-16T10:09:06.722270621Z D sandbox: Function execution started
2018-05-16T10:09:06.722387172Z D sandbox: Billing account not configured. 
    External network is not accessible and quotas are severely limited. 
    Configure billing account to remove these restrictions
2018-05-16T10:09:09.963Z I sandbox: In, data.val is 2
2018-05-16T10:09:09.971406186Z D sandbox: Function execution took 3250 ms, finished with status code: 200

我看到In, data.val is 2 三次。怎么回事?

【问题讨论】:

  • 您到底发现了什么困惑?每次调用的值是2吗?
  • 是的,我会澄清的

标签: android node.js firebase google-cloud-functions


【解决方案1】:

请记住,firebaseFunctions.getHttpsCallable("sandbox").call(data) 是异步的,这意味着它会立即返回。您的代码将快速连续启动三个调用。

还要记住,它们都共享同一个data 对象。这里可能发生的是数据的“最终”静止值包含值为 2 的 val 键。这可能是三个调用中的每一个最终将发送到函数的内容,因为循环将完成执行在每个请求发出之前。

不要在循环的每次迭代中修改相同的data,而是创建一个数据对象,并用每个请求需要的所有数据填充它(不要重复使用数据对象请求之间)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多