我有一个计划云功能。在此,我想从数据库中加载一些东西并对其进行修改。
函数运行了,但是我等不及数据库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
这是为什么?
致谢,感谢您的帮助 西蒙
答案 0 :(得分:0)
这是因为get()
方法是异步的并返回一个Promise:console.log()
方法中的then()
仅在get()
方法返回的Promise时才执行是fulfilled。另一方面,打印END
的行将立即执行,因此将“总是”出现在console.log()
中的then()
之前。
另外请注意,您没有正确返回Promise chain。我建议您观看Firebase video series上有关“ JavaScript Promises”的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()
之后执行。