【问题标题】:Return Array undefined with an async function with firestore使用带有firestore的异步函数返回未定义的数组
【发布时间】:2020-11-03 03:11:03
【问题描述】:

我有一个函数,我想用来自 firestore bd 的值返回填充数组,但我需要等待 foreach 正确填充这个数组。

我尝试了这个网站上的一些方法,但我不明白我做错了什么。

我的功能是:

static async assistencia(id) {
    console.log('Get Assistència ' + id);
    let alumnesId = id;
    var assistenciaAlumne = [];

    db.collection('alumnes')
        .doc(alumnesId)
        .collection('assistencia')
        .get()
        .then((assistencia) => {
            const promises = [];
            assistencia.forEach((assistenciaDoc) => {
                assistenciaAlumne.push([assistenciaDoc.id, assistenciaDoc.data().assistencia]);
                promises.push(db.collection('alumnes').doc(alumnesId).collection('assistencia').get());
            });
            return Promise.all(promises);
        })
        .then(function () {
            return assistenciaAlumne;
        })
        .catch((error) => {
            console.log(error);
        });
}

我使用带有此代码的按钮调用此函数:

var array = Alumnes.assistencia('0qSzBxVimwRlurLHNzXp');
    console.log(' array', array);

是的,校友,这是一门课。

基本问题是这个数组在控制台返回:

array 
Promise {<resolved>: undefined}
    __proto__: Promise
    [[PromiseStatus]]: "resolved"
    [[PromiseValue]]: undefined

我做错了什么?

【问题讨论】:

    标签: javascript jquery asynchronous google-cloud-firestore async-await


    【解决方案1】:

    现在你从then() 返回一个值,但没有人做任何有价值的事情。要从 assistencia 返回它,您需要冒泡返回值。

    return db.collection('alumnes')
      ...
    

    【讨论】:

    • 完美!我想念这个回报.. ty!
    猜你喜欢
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多