Reputation: 19703
This is my function. It simply requests a weather report every 5 minutes from an API and writes the data into a Firestore collection/document:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const fetch = require('node-fetch');
admin.initializeApp();
const db = admin.firestore();
const cors = require("cors")({ origin: true });
exports.getWeather = functions
.region('europe-west2')
.pubsub.schedule('every 5 minutes').onRun((context) => {
const weatherApiKey = '**************************';
const weatherLocation = {
'Winchelsea Beach': '354689',
'Rye': '310224',
'Hastings': '310087'
};
const weatherApiUrl = 'http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/' + weatherLocation["Winchelsea Beach"] + '?res=3hourly&key=' + weatherApiKey;
fetch(weatherApiUrl)
.then(res => res.json())
.then(json => {
db.collection("weather").doc("forecast").set({
data: json,
updatedLast: new Date().getTime()
});
});
});
The function added data to the DB successfully the very first time it ran but it doesn't run every 5 minutes, in fact it's stopped completely, and it says there's an error in my logs.
This is what is displayed in my logs:
There are no more logs after this when there should be logs every 5 minutes. If I re-deploy, it runs again with logs but then stops.
I've also checked Cloud Scheduler and it shows Result: Failed
:
I'm getting the idea that scheduled functions won't again run with bugs but I don't know what's wrong with my function to get a Function return undefined, expected Promise or value
error.
How can I resolve this?
Upvotes: 0
Views: 106
Reputation: 317322
The error message is telling you that your function should return a promise that resolves when all the async work is complete. If you don't, then the function will terminate early, and the async work is highly unlikely to complete, as Cloud Functions shuts down right afterward.
Is suggest reading the documentation to better understand how it works.
The solution is pretty straightforward. Return a promise that resolves after both the fetch and Firestore write are fully complete by chaining promises correctly.
return fetch(weatherApiUrl)
.then(res => res.json())
.then(json => {
return db.collection("weather").doc("forecast").set({
data: json,
updatedLast: new Date().getTime()
});
});
Upvotes: 1