Your mistake is that return addresses.forEach
doesn't return what you think it does.
You should follow your code and wait for every requests to come back. You can use Promise.all
for that.
I would go for something like this :
exports.getMasterTenantList = functions.https.onRequest(async(req, res) => {
await cors(req, res);
const snapshot = await admin
.database()
.ref('/property_names')
.once('value');
const result = await Promise.all(snapshot.forEach((childSnapshot) => {
const propertyName = childSnapshot.key;
const addresses = await admin
.database()
.ref(`/property_groups/${propertyName}/locations`)
.once('value');
return Promise.all(addresses.map(async(addressSnapshot) => {
const address = addressSnapshot.key;
const residents = await admin
.database()
.ref(`/property_groups/${propertyName}/locations/${address}/residents`)
.once('value');
return residents.map(resSnapshot => resSnapshot.val().name);
}));
}));
return res.status(200).send(result);
});
To understand how it works look at the following snippet example :
const cors = () => new Promise((resolve) => setTimeout(resolve, 100));
const getSnapshot = () => new Promise((resolve) => setTimeout(() => {
resolve([{
key: 'dog',
}]);
}, 100));
const getAddress = () => new Promise((resolve) => setTimeout(() => ?{
resolve([{
key: '11 richmond street',
}]);
}, 100));
const getResident = () => new Promise((resolve) => setTimeout(() =>?{
resolve([{
val: () => ({
name: 'John doe',
}),
}]);
}, 100));
async function onRequest(res) {
await cors();
const snapshot = await getSnapshot();
const result = await Promise.all(snapshot.map(async (childSnapshot) => {
const propertyName = childSnapshot.key;
const addresses = await getAddress();
return Promise.all(addresses.map(async(addressSnapshot) => {
const address = addressSnapshot.key;
const residents = await getResident();
return residents.map(resSnapshot => resSnapshot.val().name);
}));
}));
return res.status(200).send(result);
}
onRequest({
status: () => ({
send: console.log,
}),
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…