Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.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 firestore如何在JavaScrip中将doc.data()作为对象返回值传递?_Javascript_Google Cloud Firestore_Javascript Objects_Return Value - Fatal编程技术网

Javascript firestore如何在JavaScrip中将doc.data()作为对象返回值传递?

Javascript firestore如何在JavaScrip中将doc.data()作为对象返回值传递?,javascript,google-cloud-firestore,javascript-objects,return-value,Javascript,Google Cloud Firestore,Javascript Objects,Return Value,从谷歌firestore获取func文档 要编写一个返回文档数据的函数(当对象从db或dict返回时),而不仅仅是打印到Console 我有一个集合名users,我正试图从数据库中获取一个用户的数据及其密钥 由于某些原因,返回时它不会传递doc.data(),print是未定义的,尽管在函数中打印用户的数据(确保数据是在db中定义的)。我很想知道为什么 谢谢大家! var newData = getDocumentById("users","0c52f893-f0dc-4b68-a3cd-d4

从谷歌firestore获取func文档

要编写一个返回文档数据的函数(当对象从db或dict返回时),而不仅仅是打印到Console

我有一个集合名users,我正试图从数据库中获取一个用户的数据及其密钥

由于某些原因,返回时它不会传递doc.data(),print是未定义的,尽管在函数中打印用户的数据(确保数据是在db中定义的)。我很想知道为什么

谢谢大家!


var newData = getDocumentById("users","0c52f893-f0dc-4b68-a3cd-d4ffdb014375")
console.log("this is newData",newData);  // prints "this is newData undefined"

function getDocumentById(collectionType,docId){
var docRef = db.collection(collectionType).doc(docId);

docRef.get().then(function(doc) {
    if (doc.exists) {
        dataExtracted = doc.data();

        console.log(dataExtracted); //  prints the doc's data to console just fine
        return dataExtracted;
    } else {
        // doc.data() will be undefined in this case
        console.log("func getDocumentById: collection type:",collectionType,", doc type:",docId,",No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});
}

小心你在玩弄诺言。您必须使用wait或。然后才能等待结果。请尝试以下操作:

var newData = await getDocumentById("users","0c52f893-f0dc-4b68-a3cd-d4ffdb014375")
console.log("this is newData",newData);  // prints "this is newData undefined"

async function getDocumentById(collectionType,docId){
  var docRef = db.collection(collectionType).doc(docId);

  return docRef.get()
  .then(function(doc) {
    if (doc.exists) {
        dataExtracted = doc.data();

        console.log(dataExtracted); //  prints the doc's data to console just fine
        return dataExtracted;
    } else {
        // doc.data() will be undefined in this case
        console.log("func getDocumentById: collection type:",collectionType,", doc type:",docId,",No such document!");
    }
  }).catch(function(error) {
    console.log("Error getting document:", error);
  });
}

谢谢你,奥利弗!在控制台中,它打印了一个承诺,即使它在里面。然后{},它不应该返回对象本身吗?一旦存在一个有效对象,我是否可以只返回一个有效对象?您必须等待承诺得到解决,然后才能使用其输出。在里面,然后它应该显示对象,是吗