多个 Firestore 查询,单个承诺/回调 [英] Multiple Firestore queries, single promise / callback
问题描述
我了解 Firestore 不支持查询的逻辑 OR.我的想法是创建多个查询并在客户端合并结果.我正在开发一个新闻应用程序,我正在尝试获取所有包含我的用户兴趣标签(例如技术、音乐等)的文章一个普通用户有 20 个标签,所以我将提出 20 个不同的请求.
I understand that Firestore doesn’t support logical OR for queries. My idea is to create multiple queries and merge the results at the client. I am developing a news app and I am trying to fetch all articles that contain my users’ interests tags (ex. technology, music etc) An average user has 20 tags so I will be making 20 different requests.
有没有人有链接多个请求并在所有结果到达时返回唯一承诺的经验.?
Does anyone has experience with chaining multiple requests and returning a unique promise when all results arrive.?
我正在使用 js sdk
I am using the js sdk
我的数据结构:
文章(合集)
-article (document)
--id: 10
--time: 1502144665
--title: "test title"
--text: "test text"
--tags(obj)
---technology: 1502144665,
---politics: 1502144665,
---sports: 1502144665
所以我需要像下面这样创建多个数据库请求.
So I will need to create multiple db requests like the following.
user.tags = ["technology","politics","sports","architecture","business"];
for (var i = 0; i < user.tags.length; i++) {
db.collection('articles').where(user.tags[i], '>', 0).orderBy(user.tags[i]))
.get()
.then(() => {
// ... push to article array
});)
}
我想弄清楚如何在每个请求完成时创建一个承诺/回调.
I am trying to figure out how to create a promise / callback when every request finishes.
推荐答案
您可以将每个数据库访问 Promise 保存在一个数组中,然后使用 Promise.all() 以获取在每次数据库访问完成时解析的 Promise.(这段代码没有经过测试,它可能包含一些语法错误,但它演示了这个想法.)
You can save each of the database access Promises in an array, then use Promise.all() to get a Promise that resolves when each of the database accesses is complete. (This code is not tested, it may contain some syntax errors, but it demonstrates the idea.)
user.tags = ["technology","politics","sports","architecture","business"];
var dbPromises = [];
for (var i = 0; i < user.tags.length; i++) {
dbPromises.push(
db.collection('articles')
.where(user.tags[i], '>', 0)
.orderBy(user.tags[i])
.get()
);
}
Promise.all(dbPromises)
.then(() => {
// ... push to article array
};
这篇关于多个 Firestore 查询,单个承诺/回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!