无法从Node.js中的异步函数返回值

时间:2018-09-24 15:05:57

标签: javascript node.js callback promise

我正在尝试使用以下代码从Firebase DB中读取2个字段:

const policyType = readFromDb('policyType');
const claimCategory = readFromDb('claimCategory');

这是readFromDb()函数的样子,

function readFromDb (entryKey) {
var docRef = db.collection("claims").doc(entryKey);
var retValue = 'null';
docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data().entry);
        retValue =  doc.data().entry;
        console.log('ret ' + retValue);
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});
console.log('retValue ' + retValue);
return retValue;
}

我可以看到console.log('ret'+ retValue)打印出数据库中存在的字段的正确值。但是,函数readFromDb()不会返回retValue的更新值。 policyType claimCategory 的值仍为'null'。

我确实认为该函数是异步的,需要使用回调。如何使用回调成功返回字段的值?我需要创建一个通用方法,通过将entryKey作为参数来查询和获取文档的值。由于我是JavaScript和Node.js的新手,所以任何帮助将不胜感激。

0 个答案:

没有答案
相关问题