【问题标题】:Use query data from Firebase Realtime DB as input for another function使用来自 Firebase Realtime DB 的查询数据作为另一个函数的输入
【发布时间】:2021-11-02 10:19:15
【问题描述】:

所以我使用 Firebase 实时数据库来存储一些数据,并希望使用查询结果作为另一个函数的输入(生成签名 URL)。我的代码如下:

// initialize the empty list
let lista = []

// define the async function that does everything
async function queryandgeturls() {
    // make the query to the firebase realtimeDB
    await ref.orderByChild('timestamp_start').startAt(timestamp1).endAt(timestamp2).on('child_added', (snapshot) => {
        lista.push(snapshot.val().name);
    });

    // use the list as input for another function to get Signed URLs
    for (const fileName of lista) {
        const [signedUrl] = await storage.bucket(bucketName).file(fileName).getSignedUrl({
            version: 'v4',
            expires: Date.now() + 15 * 60 * 1000,
            action: 'read'
        });
        console.log(`The signed URL for ${fileName} is ${signedUrl}`);
    }
};

// call the function
queryandgeturls().catch(console.error);

到目前为止没有运气。有什么线索吗?

【问题讨论】:

  • 你想在哪里使用它们?您可以简单地从那里调用第二个函数并将它们作为参数传递?

标签: node.js firebase-realtime-database firebase-admin


【解决方案1】:

on 方法对可以重复调用的事件保持一个开放的侦听器,因此它不会返回承诺(因为承诺只能解决一次)。所以你代码中的await ref.orderByChild....on('child_added'... 没有做任何事情,这可能解释了这个问题。

要正确解决此问题,请使用once('value', ...,不要将await 和回调结合使用。

async function queryandgeturls() {
    // make the query to the firebase realtimeDB
    const results = await ref.orderByChild('timestamp_start').startAt(timestamp1).endAt(timestamp2).once('value');
    results.forEach((snapshot) => {
        lista.push(snapshot.val().name);
    });
    ...

【讨论】:

  • 工作就像一个魅力!非常感谢
猜你喜欢
  • 1970-01-01
  • 2019-04-24
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多