我的目标是一次获取多个文档。
问题是,除了一一获取,我不知道该怎么做。
我尝试过的:
fetchByDocumentIdHelper
,每个请求花费600ms。这是不可扩展的。onValue
。但是,我不知道如何获取特定的 documentId。此函数用于获取 1 个文档。
async function fetchByDocumentIdHelper(
database: Database,
documentId: string
): Promise<AgencyRealtimeModel> {
const dbRef = ref(database);
const query = child(dbRef, `agencies/${documentId}`);
const dataSnapshot = await get(query);
if (!dataSnapshot.exists()) {
return {};
}
const id = documentId;
const data = dataSnapshot.val();
const model: AgencyRealtimeModel = {
id: id,
data: data,
};
return model;
}
此功能是获取多个文档
async function fetchByDocumentIdsHelper(
database: Database,
documentIds: string[]
): Promise<AgencyRealtimeModel[]> {
const models: AgencyRealtimeModel[] = [];
for (let i = 0; i < documentIds.length; i++) {
const documentId = documentIds[i];
const model = await fetchByDocumentIdHelper(database, documentId);
models.push(model);
}
return models;
}
目前,我将使用 Promise.all
async function fetchByDocumentIdsHelper(
database: Database,
documentIds: string[]
): Promise<AgencyRealtimeModel[]> {
const models: AgencyRealtimeModel[] = await Promise.all(
documentIds.map(async (documentId) => {
const dbRef = ref(database);
const query = child(dbRef, `agencies/${documentId}`);
const dataSnapshot = await get(query);
const id = documentId;
const data = dataSnapshot.val();
const model: AgencyRealtimeModel = {
id: id,
data: data,
};
return model;
})
);
return models;
}