Leo*_*aus 3 javascript promise firebase google-cloud-firestore
我想在 JavaScript 函数中执行 Firestore 查询,但我在使用 promise 时遇到了一些困难。
假设我想从用户那里获取文档 ID。所以我创建了这个 JavaScript 函数:
function getUid(email) {
db.collection("users").where("email", "==", email)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
return doc.id;
});
})
.catch(function(error) {
return error;
});
}
Run Code Online (Sandbox Code Playgroud)
现在,当我调用该函数时res.send(getUid("user@example.com")),它返回undefined。
哪个是等待 Firestore 查询完成的正确语法?
get()是一个异步函数,所以你需要把它包装成一个async函数。此外,您没有从getUid函数中返回任何内容- 您只是在forEach参数内部返回。如果id要从快照中获取所有内容,可以使用该map功能。
async function getUids(email) {
const db = admin.firestore();
const querySnapshot = await db.collection("users").where("email", "==", email).get();
const uids = querySnapshot.docs.map((doc) => { return doc.id });
return uids;
}
exports.yourFunction = functions.http.onRequest(async (req, res) => {
const email = // ...
res.send(await getUids(email));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
947 次 |
| 最近记录: |