【发布时间】:2020-10-29 15:59:24
【问题描述】:
想要返回一个包含 [1year, 1month, etc] 的数组,每个数组都是包含每个文档的数组。
目前,这会返回一个空数组,但是当我打印快照的大小时,我会得到正确的值。不确定我是否正确使用了 push() 或者这是一个异步问题。谢谢。
exports.getStockPrices = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const currentUser = {
token: req.headers.authorization.split('Bearer ')[1]
};
// ! this is a post request
admin
.auth()
.verifyIdToken(currentUser.token)
.then(decodedToken => {
// keep this just in case we want to add anything to do with the user
const user = decodedToken;
// array of collections e.g [1year, 1mo, etc]
const data = [];
// array of documents e.g [18948901, 1984010471, etc]
const documents = [];
db.collection('historical')
.doc(`${req.body.ticker}`)
.listCollections()
.then(collections => {
// each collection is the 1year, 1mo, etc
collections.forEach(collection => {
collection.get().then(querySnapshot => {
console.log('number of documents: ' + querySnapshot.size);
querySnapshot.forEach(doc => {
// doc.data is each piece of stock data
documents.push(doc.data());
});
// each document e.g 1year, 1mo, etc
data.push(documents);
});
});
return data;
})
.then(data => {
return res.json({ data });
})
.catch(err => {
console.log(err);
return res.status(500).send({ error: 'error in getting data' });
});
})
.catch(err => {
console.log(err);
return res.status(500).send({
error: 'error authenticating user, please try logging in again'
});
});
});
});
【问题讨论】:
-
您没有正确使用 Promise。在发送最终响应之前,您必须等到所有承诺解决后。您正在发送一个空数组,因为响应是在数组填充之前发送的。如果您添加更多控制台日志记录以查看事情发生的顺序,您将看到这一点。
-
@DougStevenson 所有的承诺在哪里?我虽然我的最终 .then() 等待他们,然后发送最终响应。谢谢
-
每个
then都会立即返回并承诺。它实际上并没有阻止代码。如果您添加更多调试日志记录,您会更好地看到正在发生的事情。您将不得不更详细地了解 Promise 的工作原理。
标签: javascript node.js firebase google-cloud-firestore