if和else都被执行并且都返回结果

时间:2018-02-14 04:21:40

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

enter image description here

我的观察者字段中有2个数据,第一个有可用性孩子,第二个没有...

router.get('/getNewWatcher/:sdate/:shft/:type', function (req, res) {
    reqDate = req.params.sdate;
    reqShift = req.params.shft;
    reqType = req.params.type;

    var watcher = database.ref('watchers');

    watcher.once('value', function (snapshot) {
        var promises = [];

        snapshot.forEach(function (childSnapshot) {
            promises.push(new Promise((resolve, reject) => {
                resolve({
                    childKey: childSnapshot.key,
                    childData: childSnapshot.val()

                });
            }));
        });
        Promise.all(promises).then(function (snapshot) {
            var dataSet =[];

            snapshot.forEach(function (result) {
                if (result.childData.availability) {                            
                    dataSet.push({
                        child: result
                    })
                }else {
                    dataSet.push({
                        child: 'No Available Watchers'
                    })
                }
            });
            res.json(dataSet);
        })
    });
});

我的代码有效..当我运行此脚本以检查观察者是否具有可用性子时,它将返回具有可用性子级的观察者..但由于某种原因,else条件也返回'No Available Watchers'所以我的问题是,当我运行此脚本时,我的ifelse条件都会返回一个不是我正在寻找的结果,而我无法弄明白为什么。< / p>

2 个答案:

答案 0 :(得分:0)

Here is my Firebase architecture

我在Swift中使用了相同的东西,这里的代码可能对它有用。

    databaseRef.child("users").child(key).child("following").observeSingleEventOfType(.Value, withBlock: { snapshot in

        if let following = snapshot.value as? [String : AnyObject] {

            self.lblFollowing.text = String(following.count)

        } else {

            self.lblFollowing.text = "00"

        }
    })

答案 1 :(得分:0)

在您与Jaromanda X的评论链中,我的印象是您想要返回一个可用的观察者列表,一个&#34;没有可用的观察者&#34;什么时候没有观察者可以使用。

要做到这一点,你必须移动&#34;根本没有观察者&#34;在循环外检测:

var dataSet =[];

snapshot.forEach(function (result) {
    if (result.childData.availability) {                            
        dataSet.push({
            child: result
        })
    }
});

if (dataSet.length === 0) {
    dataSet.push({
        child: 'No Available Watchers'
    })
}

res.json(dataSet);
相关问题