【发布时间】:2021-01-28 23:42:41
【问题描述】:
我正在尝试将三次嵌套循环中的结果推送到结果数组中,最后返回该数组。我认为拥有 .then 会实现我正在寻找的行为,但该函数会立即返回一个空数组。我尝试过使用 async/await、.map 和 for 循环的变体,但没有成功。
exports.getMasterTenantList = functions.https.onRequest((req, res) => {
let result = [];
cors(req, res, () => {
admin
.database()
.ref("/property_names")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
const propertyName = childSnapshot.key;
admin
.database()
.ref(`/property_groups/${propertyName}/locations`)
.once("value")
.then((addresses) => {
return addresses.forEach((addressSnapshot) => {
const address = addressSnapshot.key;
admin
.database()
.ref(`/property_groups/${propertyName}/locations/${address}/residents`)
.once("value")
.then((residents) => {
return residents.forEach((resSnapshot) => {
result.push(resSnapshot.val().name);
});
})
.catch((error) => {
console.log(error);
});
});
})
.catch((error) => {
console.log(error);
});
});
return res.status(200).send(result);
})
.catch((error) => {
console.log(error);
});
});
});
【问题讨论】:
-
为什么主执行在
cors中间件里面?此外,您可以通过返回 Promise 而不是在另一个 Promise 中创建 Promise 来避免这种嵌套。
标签: javascript node.js promise