Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript doc.data();从firebase返回未定义但正常打印?_Javascript_Database_Firebase_Return_Undefined - Fatal编程技术网

Javascript doc.data();从firebase返回未定义但正常打印?

Javascript doc.data();从firebase返回未定义但正常打印?,javascript,database,firebase,return,undefined,Javascript,Database,Firebase,Return,Undefined,所以我需要从firebase集合中获取具有给定id的数据。然后,我的函数应该返回它(文档),并在测试中打印它(作为“结果”)。出于某种原因,我的测试打印“未定义”,但我的函数(getIteration(id))打印出我需要它返回的内容(在返回上方的console.log)。为什么它返回的是未定义的,但使用的是相同的doc.data()打印我需要的内容 这是我的密码: //gets the iteration with the given id async function getIteratio

所以我需要从firebase集合中获取具有给定id的数据。然后,我的函数应该返回它(文档),并在测试中打印它(作为“结果”)。出于某种原因,我的测试打印“未定义”,但我的函数(getIteration(id))打印出我需要它返回的内容(在返回上方的console.log)。为什么它返回的是未定义的,但使用的是相同的doc.data()打印我需要的内容

这是我的密码:

//gets the iteration with the given id
async function getIteration(id) {
    fb.db.collection('iteration').where('id', '==', id).get().then(snapshot => {
        snapshot.forEach(doc => {
            console.log(doc.data())
            return doc.data();
        })
    })
}
还有我的测试:

firebase.getIteration(fbIterationID).then(function(result){
 console.log('LOGGING FB ITERATION DOCUMENT WITH THE ID OF: ' + fbIterationID)
    console.log(result)
})

您需要从
getIteration
返回承诺,以便调用者可以使用其结果。将函数设置为异步并不能为您实现这一点:

async function getIteration(id) {
    return fb.db...
}

这样地?这仍然给了我未定义的:(
异步函数getIteration(id){return fb.db.collection('iteration').where('id','==','id').get().then(snapshot=>{snapshot.forEach(doc=>{console.log(doc.data())return doc.data();})}
虽然此代码可能提供问题的解决方案,但最好添加其工作原因/方式的上下文。这可以帮助未来用户学习,并将这些知识应用到他们自己的代码中。在解释代码时,用户也可能会以投票的形式给予积极反馈。
    //gets the iteration with the given id
async function getIteration(id) {
    return fb.db.collection('iteration').where('id', '==', id).get().then(snapshot => {
        return snapshot.docs.map(doc => doc.data());
    })
}