Undefined不是React Native和Firebase的对象

时间:2018-01-14 18:27:52

标签: javascript firebase react-native firebase-realtime-database

我正在使用CRNA构建一个React-Native应用程序(节点:v9.3.0,npm:4.6.1,RN:0.50.4 React:16.0.0)。

我的控制台给出了以下错误:     “undefined不是一个对象(评估'secciones.forEach')”

有错误的代码如下:

async buscarProfesores(secciones) {
    const profesores = [];
    secciones.forEach(seccion => {
        firebase.database().ref(`/Usuarios/${seccion.profesor}`).on('value', async snapshot => {
            const prof = snapshot.val();
            await profesores.push(prof.nombre);
        }); 
    });
    return await profesores;}


async buscarSecciones() {
    try {
        const usuario = firebase.auth().currentUser.uid;
        let secciones;
        await firebase.database().ref(`/Usuarios/${usuario}`)
            .on('value', snapshot => {
                secciones = snapshot.val().secciones;
                return false;
            });
        return secciones;
    } catch (error) {
        console.log(error);
    }
}

我正在调用buscarProfesores函数是这个片段:

async auxiliar() {
    try {
        const secciones = await this.buscarSecciones();
        const profesores = await this.buscarProfesores(secciones);
        const data = await this.armarSnapshot(secciones, profesores);
        return data;
    } catch (error) {
        console.log(error);
    }
}

1 个答案:

答案 0 :(得分:0)

我想我可以识别代码中的一些问题,

buscarProfesores

async buscarProfesores(secciones) {
    let profesores = []; // Not 'const', because 'profesores' is not read-only
    secciones.forEach((seccion) => {
        firebase.database().ref(`/Usuarios/${seccion.profesor}`).once('value', (snapshot) => {
            profesores.push(snapshot.val().nombre);
            // It shouldn't be 'async (snapshot) => { ... }', because
            // What you're doing here is not an async operation, you're simply
            // pushing something into an array. If anything is async, it's this:
            //
            // secciones.forEach(async (seccion) => { firebase.database()... });
        });
    });

    // await return profesores
    // Again, there shouldn't be 'await' here, and even if there isn't await here,
    // all you'll get is an empty array, because 'firebase.database()...' is an
    // async operation, it will be executed, but it will take some amount of time,
    // and meanwhile, the rest of the function will be executed at the same time,
    // meaning that, the return statement will be executed immediately, therefore,
    // you have an empty array
}

因此,您应该重新编写buscarProfesores函数。你在buscarSecciones()函数中得到了它几乎完美,只需以相同的方式编写这个函数,你就在正确的轨道上。但是,不同之处在于您从数据库中获取了许多内容并将它们放入此函数中的数组中,您需要Promise.all()的一点帮助:

async buscarProfesores(secciones) {
    let promises = [];
    secciones.forEach((seccion) => {
        promises.push(firebase.database().ref(`/Usuarios/${seccion.profesor}`).once('value'));
    });

    await Promise.all(promises)
        .then((results) => {
            let profesores = [];
            results.forEach((result) => {
                profesores.push(result.val().nombre);
            });

            return profesores;
        })
        .catch((error) => {
            console.log(error);
            return [];
        });
}

Promise.all()获取一系列promises并执行它们,只有当所有promises成功执行后才会执行.then(),否则.catch()将被执行

buscarSecciones()功能没有太大问题,只需将.on更改为.once,然后删除return false语句