node.js - 从 Firestore 获取异步值
问题描述
我正在努力处理异步操作。我试图简单地从 firestore 获取一个值并将其存储在一个 var 中。
我设法接收到该值,我什至可以在我专门这样做时将其保存在 var 中(在 get 函数中使用 var ),但是在尝试以灵活的方式保存它时,我似乎没有正确管理等待:
async function getValues(collectionName, docName,) {
console.log("start")
var result;
var docRef = await db.collection(collectionName).doc(docName).get()
.then(//async// (tried this as well with async) function (doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
result = doc.data().text;
console.log(result);
return //await// (this as well with async) result;
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
result = "No such document!";
return result;
}
console.log("end");
}).catch (function (err) {
console.log('Error getting documents', err);
});
};
helpMessage = getValues('configuration','helpMessage');
注意:doc.data().text -> "text"
是存储我的值的字段的名称。我必须在这里使用.value
吗?
我在控制台中得到的结果是:
info: 文档数据: { text: '来自数据库的正确文本' }
info: 来自数据库的正确文本
但是在我的代码中使用 helpMessage 我得到了
{}
来自 Telegram 机器人的图像,我在其中尝试使用 helpMessage 作为对“/help”命令的响应。
我已经检查过:从 cloud firestore 获取值, Firebase Firestore get() async/await,从 firebase firestore 引用获取异步值,最重要的是如何从异步调用返回响应?. 他们要么处理多个文档(使用 forEach),要么不解决我的问题的异步性质,要么(最后一种情况),我根本无法理解它的性质。
此外,nodejs 和 firestore 似乎都在快速发展,很难找到好的、最新的文档或示例。任何指针都非常有用。
解决方案
你有错误的方式。这比你想象的要容易得多。
function getValues(collectionName, docName) {
return db.collection(collectionName).doc(docName).get().then(function (doc) {
if (doc.exists) return doc.data().text;
return Promise.reject("No such document");
}};
}
如果函数返回一个承诺(如db.collection(...).doc(...).get()
),则返回该承诺。这是上面的“外部” return
。
在 Promise 处理程序中(在.then()
回调内部),返回一个值来表示成功,或者返回一个被拒绝的 Promise 来表示错误。这就是上面的“内在” return
。throw
如果你愿意,你也可以返回一个错误,而不是返回一个被拒绝的承诺。
现在你有了一个返回承诺的函数。您可以将其与.then()
and一起使用.catch()
:
getValues('configuration','helpMessage')
.then(function (text) { console.log(text); })
.catch(function (err) { console.log("ERROR:" err); });
或者await
它在async
try/catch 块中的函数中,如果你更喜欢它:
async function doSomething() {
try {
let text = await getValues('configuration','helpMessage');
console.log(text);
} catch {
console.log("ERROR:" err);
}
}
如果你想在你的getValues()
函数中使用 async/await,你可以:
async function getValues(collectionName, docName) {
let doc = await db.collection(collectionName).doc(docName).get();
if (doc.exists) return doc.data().text;
throw new Error("No such document");
}
推荐阅读
- python - :{ AttributeError: 'int' 对象在 Python 中没有属性 'config'
- json - 从 JSON 文件中删除重复的 JSON 表示
- python - Tkinter 中的全局热键
- json - 将解码的 JSON 值保存在 Lua 变量中
- android - 在 Android 10 及更高版本中将图像共享到其他应用程序而不将其永久保存在设备存储中
- java - JavaFX 15 TableView 不显示信息
- javascript - 在javascript中睡觉,为什么它不循环?
- javascript - next.js firebase 错误 .a.storage 不是函数
- php - 如何在 Laravel 本地化中的 hreflang 标签中设置语言环境前缀
- python - 当切片列表是递归函数中的参数时,Python 是否会创建一个新列表?