以下Cloud Function仅返回第一个数据而不是10:
exports.viewdata = functions.https.onRequest((req, res) => {
const userId = req.query.user;
return admin.database().ref('users/' + userId)
.orderByKey()
.limitToLast(10)
.on('child_added', function(snapshot) {
snapshot.forEach(function(data) {
res.status(200).send(data.val());
});
});
});
请帮我解决这个问题。
答案 0 :(得分:2)
使用send()
,end()
或redirect()
将terminate a HTTP Cloud Function:
始终使用
send()
,redirect()
或end()
结束HTTP功能。否则,您的功能可能会继续运行并被系统强行终止。
在您的示例中,您在每个子快照的res.status(200).send(data.val());
次迭代中调用forEach
,因此它只有机会发送一个响应。
同样,因为您使用了child_added
event listener,所以对于指定路径的每个孩子都会触发一次。
如果您需要一次回复所有查询数据,最好使用value
event listener,这样可以在一个响应中检索查询中的所有数据:
exports.viewdata = functions.https.onRequest((req, res) => {
const userId = req.query.user;
admin.database().ref('users/' + userId)
.orderByKey()
.limitToLast(10)
.on('value', function(snapshot) {
res.status(200).send(snapshot.val());
});
});
但是,如果您打算单独为每个孩子建立一个回复,则可以使用res.write()
将数据写入回复,然后最终使用end()
发送:
exports.viewdata = functions.https.onRequest((req, res) => {
const userId = req.query.user;
admin.database().ref('users/' + userId)
.orderByKey()
.limitToLast(10)
.on('value', function(snapshot) {
snapshot.forEach(function(data) {
res.write(data.val());
});
res.status(200).end();
});
});
或者,您可以将它们添加到列表中,然后再将它们作为响应发回。你在这里采取的方法都取决于你的最终目标。
与您的初步问题无关,但为了完整起见,请参阅以下观察和附注:评论:
HTTPS触发器不需要return
admin.database().ref()
语句,因为它们有different lifecycle than other triggers而且不需要返回承诺。
如果您在检索到必要数据后无需听取进一步的更改,则应考虑使用once()
(至read data once)代替on()
或使用off()
移除on()
听众。