最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin28浏览0评论

检索 Firebase 实时数据库节点数据时的 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++
    }
})
发布评论

评论列表(0)

  1. 暂无评论