0

我正在尝试从所有用户集合中获取所有票证,firestore并且我使用此功能

const { Firestore } = require('@google-cloud/firestore');
const firestore = new Firestore();

const GetAllUsersTickets = async () => {
    const usersRef = await firestore.collection('users').get();
    const usersTicketsRef = await usersRef.docs.map(user => user.ref.collection('tickets'));
    const tickets = await usersTicketsRef.map(el => el.get())
    tickets.map(ticket => ticket.then(snap => snap.docs.map(el => console.log(el.data()))))
}

是否有另一种方法来获取返回的数据,promise而不是使用then

4

2 回答 2

0

使用 for-of 循​​环

for-of 循​​环支持使用 await 等待异步调用或操作。

const usersRef = await firestore.collection('users').get();
const usersTicketsRef = usersRef.docs.map(user => user.ref.collection('tickets'));

for (const ticketRef of usersTicketsRef) {
  const ticket = await ticketRef.get();

  console.log(ticket.data());
}

.then()当您需要按照您的案例中描述的方式遍历所有项目时,这可能是一个很好的方式来使用。

改进数据结构

请注意,如果您经常访问数据库,您可能想要创建更有效的查询,或者以更非规范化的方式构建数据。

于 2021-01-11T23:54:07.313 回答
0

我很确定我会将代码编写为:

 const GetAllUsersTickets = async () => {
    //the .get() is asynchronous
    const usersRef = await firestore.collection('users').get();

    //the below just creates an array of references to ticket COLLECTIONS for each user
    //it's synchronous; no need for await
    const usersTicketsRef = usersRef.docs.map(user => user.ref.collection('tickets'));

    //the following .get()'s ARE asynchronous, but .map() isn't -
    // so we need Promise.All() - the .then() hack attempts to wait for each, but the 
    // promise.all is a little clearer
    const tickets = await Promise.all(usersTicketsRef.map(el => el.get()));

    //at this point, tickets is an array of snapshots, so the following is synchronous
    tickets.map(ticket => (snap => snap.docs.map(el => console.log(el.data()))))
  }
于 2021-01-11T23:46:21.277 回答