'function returned undefined and promises is not defined in functions firebase
This is my first firebase function and it gives me a lot of headic :) The purpose is to update the count field from all documents from collection users every 24 hours.
async function clearCountField() {
console.log("Clearing count task start point.");
const userSnapshots = db.collection('users').where('count', '!=', '').where('nou', '==', false).get().then(snapshot => {
const promises = [];
snapshot.forEach(doc => {
promises.push(doc.ref.update({ 'count': '' }));
});
});
return Promise.all(promises)
}
export const ClearCountField24h = functions.pubsub.schedule('0 0 * * *')
.timeZone('Europe/Bucharest') // timezone
.onRun((context) => {
const promise = clearCountField().then(resolve,reject);
});
what do I do wrong?
Solution 1:[1]
The promises created in the forEach
loop are never resolved because Promise.all()
is being returned before the query completes. Fix it like this:
async function clearCountField() {
const query = db.collection('users').where('count', '!=', '').where('nou', '==', false);
return query.get().then(snapshot => {
const promises = snapshot.docs.map(doc => doc.ref.update({ 'count': '' }));
return Promise.all(promises)
}
}
The then
in your export function is superfluous. Just return the promise from clearCountField()
export const ClearCountField24h = functions.pubsub.schedule('0 0 * * *')
.timeZone('Europe/Bucharest') // timezone
.onRun((context) => {
return clearCountField();
});
Solution 2:[2]
Changing the following:
export const ClearCountField24h = functions.pubsub.schedule('0 0 * * *')
.timeZone('Europe/Bucharest') // timezone
.onRun((context) => {
const promise = clearCountField().then(resolve,reject);
}
);
To this:
export const ClearCountField24h = functions.pubsub.schedule('0 0 * * *')
.timeZone('Europe/Bucharest') // timezone
.onRun((context) => {
return clearCountField().then(resolve,reject);
}
);
Made one issue go away... but when testing the function the Error: ReferenceError: promises is not defined
still remains...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Zach Jensz |