检索 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++
}
})