检索 Firebase 实时数据库节点数据时的 NodeJS 竞争条件

编程入门 行业动态 更新时间:2024-10-04 01:19:48

检索 Firebase 实时数据库<a href=https://www.elefans.com/category/jswz/34/1771452.html style=节点数据时的 NodeJS 竞争条件"/>

检索 Firebase 实时数据库节点数据时的 NodeJS 竞争条件

以下 nodejs 竞争条件有问题(我相信它叫)。

我正在尝试获取 Pool ID 是一个

下面是我的代码,下面是输出:

for(;currPool<=lastPool;) {

    console.log("Current Pool ID: " + currPool);

    poolsRef.child(currPool).child("PoolType").once('value', function(snapshot) {
        
        if (snapshot.exists()) {
        
            const poolType = snapshot.val();
            //
            console.log("Pool ID:", currPool, "is a:", poolType , " Style PoolType");

         }

    });

    currPool++;

}

输出如下:

Current Pool ID: 11018
Current Pool ID: 11019
Current Pool ID: 11020
Current Pool ID: 11021
Current Pool ID: 11022
Current Pool ID: 11023
Pool ID: 11024 is a: Survivor  Style PoolType
Pool ID: 11024 is a: Pickem  Style PoolType
Pool ID: 11024 is a: Pickem  Style PoolType
Pool ID: 11024 is a: Pickem  Style PoolType
Pool ID: 11024 is a: Pickem  Style PoolType
Pool ID: 11024 is a: Survivor  Style PoolType

我如何让它显示:

Pool ID: 11018 is a: Survivor  Style PoolType
Pool ID: 11019 is a: Pickem  Style PoolType
Pool ID: 11020 is a: Pickem  Style PoolType
Pool ID: 11021 is a: Pickem  Style PoolType
Pool ID: 11022 is a: Pickem  Style PoolType
Pool ID: 11023 is a: Survivor  Style PoolType
回答如下:

你在循环中有一个回调。关于这个问题有很多问题,比如这个,但是让你的代码与 for 循环一起工作并不理想。

您正在使用 for 循环来完成 while 循环的工作。如果要使用 for 循环,则在 for 语句中使用

currPool++
。或者改用 while 循环:

while (currPool <= lastPool) {
    // rest of the code
    currPool++
}

根据文档,

.on
需要回调,而
.once
can 需要回调,但也会返回一个 Promise,这将有助于扁平化代码并解决异步问题:

;(async () => {
    while (currPool <= lastPool) {
        console.log("Current Pool ID: ", currPool)
        const snapshot = await poolsRef.child(currPool)
            .child("PoolType")
            .once("value")
        if (snapshot.exists()) {
            const poolType = snapshot.val()
            console.log("Pool ID:", currPool, "is a:", poolType , " Style PoolType")
        }
        currPool++
    }
})

更多推荐

检索 Firebase 实时数据库节点数据时的 NodeJS 竞争条件

本文发布于:2024-05-30 20:44:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   实时   条件   竞争   数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!