响应的异步Firebase查询 [英] Asynchronous Firebase query to response

查看:77
本文介绍了响应的异步Firebase查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从firebase集合中获取所有文档,创建一个列表,并根据需要使用Cloud Function返回它,但是我在JavaScript的异步特性方面苦苦挣扎.到目前为止,这是我的代码:

I'm trying to get all documents from a firebase collection, create a list and return it on request with a Cloud Function, but I'm struggling with the asynchronous nature of JavaScript. Here's my code so far:

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

const items = "";

async function buildItems() {
    db.collection("reminders").get().then((QuerySnapshot) => {
        QuerySnapshot.forEach((item) => {
            items.concat("<li>" + item.data().name + "</li>");
            console.log(items);
        });
    })
}
exports.view = functions.https.onRequest((req, res) => {
    buildItems().then(
        res.status(200).send(`<!doctype html>
    <head>
      <title>Reminders</title>
    </head>
    <body>
      <ul>
        ${items}
      </ul>
    </body>
  </html>`))});

包括我尝试过的基于承诺的代码(这是错误的,我不知道如何解决)

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

function buildItems() {
    return new Promise((resolve) => {
        resolve(db.collection("reminders").get())
    });
}
exports.view = functions.https.onRequest((req, res) => {
    buildItems(reminders => {
        let items = "";
        reminders.then((qs) => {
            qs.forEach(items.concat("<li>" + qs.data().name + "</li>"))
        }).then(resolve(items));
    }).then( items =>
        res.status(200).send(`
  <!doctype html>
    <head>
      <title>Reminders</title>
    </head>
    <body>
      <ul>
        ${items}
      </ul>
    </body>
  </html>`))});

输出始终是相同的:绝对没有任何内容显示在浏览器或控制台上.我已经尝试过此代码的变体,但到目前为止没有成功.

The output is always the same: absolutely nothing is displayed on the browser or to the console. I've tried variations of this code, but no success so far.

提前谢谢!

推荐答案

我稍微清理了一下代码,并用async await替换了基于Promise的代码.您可以尝试运行此代码:

I cleaned the code up a bit and replaced your Promise based code with async await. You can try running this:

异步等待版本

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

const buildItems = async () => {
  return db.collection('reminders').get();
};

exports.view = functions.https.onRequest(async (req, res) => {
  try {
    const reminders = await buildItems();
    let items = '';

    reminders.forEach(qs => {
      items.concat(`<li> ${qs.data().name} </li>`);
    });

    return res
      .status(200)
      .send(`
        <!doctype html>
        <head>
            <title>Reminders</title>
            </head>
            <body>
            <ul>
                ${items}
            </ul>
            </body>
        </html>
        `);
  } catch (error) {
    /** Handle error here */
  }
});

基于承诺的版本

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

const buildItems = () => {
  return db.collection('reminders').get();
};

exports.view = functions.https.onRequest((req, res) => {
  buildItems()
    .then(reminders => {
      let items = '';
      reminders.forEach(qs => {
        items.concat(`<li> ${qs.data().name} </li>`);
      });

      return res
        .status(200)
        .send(`
        <!doctype html>
        <head>
            <title>Reminders</title>
            </head>
            <body>
            <ul>
                ${items}
            </ul>
            </body>
        </html>
        `);
    })
    .catch(error => {
      /** Handle Error here */
    });
});

如果仍然遇到问题,则应尝试检查集合reminders中是否确实包含要获取的文档.

If you are having still having trouble, you should try if the collection reminders actually contains the documents you want to fetch.

.size属性在Firebase查询快照结果的[QuerySnapShots][1]中可用.如果快照大小为0.

The .size property is available in [QuerySnapShots][1] in Firebase query snapshot results. If the snapshot size is 0.

这篇关于响应的异步Firebase查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆