【问题标题】:make express wait for firebase query before sending response在发送响应之前让 express 等待 firebase 查询
【发布时间】:2021-02-10 20:26:44
【问题描述】:

我正在尝试 Firebase,我加入了两个表,并希望 node js express 在两个查询结果可用后发送响应

const database = firebase.database().ref();

const posts = database.child('posts');
const user = database.child('user');

let postWithName = [];
let postnames = []


function getUserNames(data) {
    if (data) {
        postnames = [] // NEW
        Object.values(data).forEach((value) => {
            user.child(value.user_id).once('value', sn => {
                let content = value.content;
                let date_posted = value.date_posted;
                let id = value.id;
                let title = value.title;
                let user_id = value.user_id;
                let user_Name = sn.val().name;
                postnames.push({
                    "id": id,
                    "title": title,
                    "date_posted": date_posted,
                    "content": content,
                    "user_Name": user_Name,
                    "user_id": user_id
                })
                postWithName = postnames.sort(function (a, b) {
                    return b.id - a.id;
                })
                console.log(postnames)
            })

        })
    }
}
function GetAll() {
    posts.once('value', snap => {
        postdata = snap.val()
        getUserNames(postdata)
    })

}

app.get('/getPosts', function (req, res) {
    GetAll()

    res.send({ "posts": postWithName })

})

方案是这样的 用户表示例:

8721da2c-0028-430f-a995-0d03c8abb393:{
  IsAdmin: 0,
  Password: 123456,
  email: 'admin@test.com',
  id: 1,
  image_file: 'https://i.imgur.com/fjYAIbl.png',
  name: 'Abdelrahman',
  phone: 1234567890,
  public_id: '8721da2c-0028-430f-a995-0d03c8abb393'
}

发布表示例:


6:{
    content: 'content 4',
    date_posted: '2021-01-06 08:54:44',
    id: 6,
    title: 'test 4',
    user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
  },

当使用提供的代码时,我在第一次获取请求时没有获取数据,但是在它之后我根据需要获取数据,我只需要请求等待 firebase 查询完成并填充列表然后发送回应,怎么办?

【问题讨论】:

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


    【解决方案1】:

    您可以将 async/await 与您的 rest api 服务一起使用。 欲了解更多信息,您可以访问:点击here

    【讨论】:

    • 尝试了异步等待,但它仍然不会等待整个查询具有最终值,如果您使用 firebase 尝试它,我会欣赏使用等待和连接查询的示例
    【解决方案2】:

    不是一个理想的解决方案,但您可以使用 setTimeout 函数将 res.send 延迟大约两到三秒,直到查询得到解决。 将此作为您的最后一个解决方案,因为它会影响性能

    【讨论】:

      【解决方案3】:

      我认为您可以简单地在 foreach 中设置 if 条件,以便当 res 数组的长度等于 data 数组时,您将发送响应

       if (postWithName.length == data.length) {
                          res.send({ "posts": postWithName })
                      }
      
      

      希望能帮到你

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 2021-12-22
        • 2018-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多