JavaScript数组不可迭代 [英] JavaScript array not iterable

查看:183
本文介绍了JavaScript数组不可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨晚我用一个简单的JavaScript数组遇到了一个非常奇怪的问题.我正在开发一个由Firebase驱动的React Native应用程序,并使用SDK从实时数据库中获取数据.

I hit a really weird issue with a simple JavaScript array last night. I am working on a React Native app powered by Firebase and getting data from the real-time database with the SDK.

这是代码:

    var app = this

    this.props.fb.auth().onAuthStateChanged(function(user) {
        if (user) {
            app.props.fb.database().ref('/users/' + user.uid + "/timeline").once('value').then(function(snapshot) {
                var posts = snapshot.val()
                return posts
            }).then((posts) => {                
                var statuses = [];
                for (i in posts) {

                    app.props.fb.database().ref('/posts/' + posts[i]).once('value').then(function(snapshot) {
                       statuses.push(snapshot.val())
                    });
                }

                console.log(statuses)
            })
        }

    });

上面的代码应该从每个用户的 timeline 中获取数据,依次遍历 timeline timeline 上的每个 posts 然后从 posts 获取帖子的数据.然后,它只是将数据推送到 statuses 数组,该数组最后被控制台记录.

The above code is supposed to get the data from the timeline of each user, iterate through each of the posts on the timeline and then get the data of the post from posts. It then simply pushes the data to the statuses array, which is being console logged at the end.

这是控制台上显示的内容.

This is what shows up on the console.

在展开数组之前,控制台不会显示数组中的项目.另外,当我尝试获取数组的 length 时,它返回0,而且我也无法遍历数组中的项目.

Until the array is expanded, the console doesn't show the items in the array. Additionally, when I try to get the length of the array, it returns 0 and I also can't iterate through the items on the array.

我在做什么错了?

推荐答案

如果帖子是可迭代的,我会考虑使用某种版本的q.all,然后在所有promise都解决了之后,您就可以可靠地记录所有push结果分成状态数组.

If posts is an iterable I would look into using some version of q.all and then when all promises are resolved you can reliably log the result of push all those pieces into the statuses array.

一些伪代码:

if (user) {
        app.props.fb.database().ref(`/users/${user.uid}/timeline`)
        .once('value')
        .then(snapshot => snapshot.val())
        .then(posts => {                
            const statuses = [];

            const promises = Object.keys(posts).map(key => {
                return app.props.fb.database().ref(`/posts/${posts[key]}`).once('value')
                    .then(snapshot => statuses.push(snapshot.val()));
            }

            return Promises.all(promises)
        })
        .then(() => console.log(statuses));
    }

这篇关于JavaScript数组不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆