javascript - 云函数等待数据库请求
问题描述
我有一个日程云功能。在这个我想从数据库中加载一些东西并修改它。
函数运行,但我等不及数据库 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
为什么是这样?
问候和感谢西蒙的帮助
解决方案
这是因为该get()
方法是异步的,并且返回一个 Promise:方法中的console.log()
s 只有在该方法返回的 Promise被实现then()
时才会执行。另一方面,打印的行会立即执行,因此将“总是”出现在 .s中的 s之前。get()
END
console.log()
then()
另外请注意,您没有正确返回Promise 链。我建议您观看 Firebase视频系列中关于“JavaScript Promises”的 3 个视频。这是 Cloud Functions 的一个关键点。
因此,您应该执行以下操作:
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 之后执行。