我有一个schedule Cloud函数。在这个我想加载一些东西从数据库和修改它
函数运行了,但我等不及数据库Stuff了。
希望你能看到一个错误并帮助我…
我的代码
exports.notifysmall = functions.pubsub.schedule('0 15 * * *')
.timeZone('Europe/Berlin').onRun((context) => {
const db = admin.firestore();
console.log("#################START RUN################");
db.collection("user").get().then((snapshot: any) => {
snapshot.forEach((record: any) => {
console.log(record.get("name"));
});
return true;
}).catch((err: any) => {
console.log("#################ERROR################");
});
console.log("#################END################");
return true;
});
我想在日志中看到的是:
#################START RUN################
user1
user2
user3
#################END################
我现在是这样的:
#################START RUN################
#################END################
user1
user2
user3
为什么会这样?
问候并感谢您的帮助Simon
这是因为get()
方法是异步的并返回Promise:只有当get()
方法返回的Promise得到满足时,才会执行then()
方法中的console.log()
s。另一方面,打印END
的行将立即执行,因此将"始终"位于then()
中的console.log()
之前。
此外,请注意,您没有正确返回Promise链。我建议您观看Firebase系列视频中关于"JavaScript承诺"的3个视频这是云功能的一个关键点。
因此,您应该执行以下操作:
exports.notifysmall = functions.pubsub.schedule('0 15 * * *')
.timeZone('Europe/Berlin').onRun((context) => {
const db = admin.firestore();
console.log("#################START RUN################");
return db.collection("user").get() // <--- See the return
.then((snapshot: any) => {
snapshot.forEach((record: any) => {
console.log(record.get("name"));
});
console.log("#################END 1 ################");
return true;
}).catch((err: any) => {
console.log("#################ERROR################");
return true;
});
console.log("#################END 2 ################");
});
您应该看到的上述代码如下:
#################START RUN################
#################END 2 ################
user1
user2
user3
#################END 1 ################
打印END 1
的行将在其他console.log()
s之后执行,如上所述。