我每天晚上都使用下面的代码删除所有旧数据。
每个函数本身都很好,如果我创建多个调度任务,每个函数一个,它也很好。但是,当我将它们组合到一个名为scheduledCleanData的Scheduled Task中时,我会收到错误:无法加载默认凭据。浏览到https://cloud.google.com/docs/authentication/getting-started了解更多信息。在GoogleAuth.getApplicationDefaultAsync(/workspace/node_modules/google-auth-library/build/src/auth/GoogleAuth.js:161:19(正在处理中_tickCallback(internal/process/next_tick.js:68:7(
根据这篇文章,我认为这是由于函数没有等待回调,而不是凭据问题。但是,添加async或wait关键字会导致解析错误。其中一些集合需要删除数千条记录。
任何关于如何修改此代码以正确等待的帮助都将不胜感激!
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const client = require('firebase-tools');
admin.initializeApp(functions.config().firebase)
const db = admin.firestore();
const runtimeOpts = {
timeoutSeconds: 300,
memory: '1GB'
}
exports.scheduledCleanData = functions
.runWith(runtimeOpts)
.pubsub.schedule('0 3 * * *')
.timeZone('America/Chicago')
.onRun((context) => {
return cleanOldAssignments()
.then(cleanOldDuties())
.then(cleanOldEvents())
.then(console.info("scheduledCleanData Complete!"));
});
function cleanOldAssignments() {
const dateYesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); // 24 hours
return db.collectionGroup('assignments').where('date', '<', dateYesterday).get()
.then(querySnapshot => {
console.info("Old assignments to remove: " + querySnapshot.size);
const promises = [];
querySnapshot.forEach(doc => {
promises.push(doc.ref.delete());
});
return Promise.all(promises);
});
}
function cleanOldDuties() {
const dateYesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); // 24 hours
return db.collectionGroup('duties').where('date', '<', dateYesterday).get()
.then(querySnapshot => {
console.info("Old duties to remove: " + querySnapshot.size);
const promises = [];
querySnapshot.forEach(doc => {
promises.push(doc.ref.delete());
});
return Promise.all(promises);
});
}
function cleanOldEvents() {
const dateYesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); // 24 hours
return db.collectionGroup('events').where('date', '<', dateYesterday).get()
.then(querySnapshot => {
console.info("Old events to remove: " + querySnapshot.size);
const promises = [];
querySnapshot.forEach(doc => {
promises.push(doc.ref.delete());
});
return Promise.all(promises);
});
}
如果cleanOldDuties
和cleanOldEvents
都返回了更多的promise,则您的代码没有将它们考虑在内。您需要显式地返回它们的值,以便沿承诺链传播:
return cleanOldAssignments()
.then(() => { return cleanOldDuties() })
.then(() => { return cleanOldEvents() })
如果没有看到这些其他函数的确切代码,就不确定这是否有效。这些功能也必须正确执行。
async/await几乎总是一种更清晰的方式来表达这些东西。你可能只是错误地使用了它们。