I have an async/await problems (I know, I know) that makes no sense to me. I'm declaring both functions (child and HOF) as async, and awaiting the returned results before trying to console log them. Surprise surprise, I get pending. The function hangs for 60s and times out (so it seems even my runWith
timeout method isn't working. Also tried logging a simple "here" right before declaring const fetchData
, but also that didn't log. And yet console logging after actually calling the fn does...
exports.getBitcoinPrice = functions
.region("europe-west1")
.runWith({ timeoutSeconds: 5 })
.https.onRequest(async (req, res) => {
const fetchData = async () => {
return await axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json", {
timeout: 2000,
})
.then((res) => res.json())
.catch((error) => console.log(error));
};
const data = await fetchData();
console.log(await data);
return null;
});
I wanted to use fetch
but apparently node-fetch
doesn't work well with firebase.
I will try to provide a list of the many SO posts and articles I've read about async/await. I've done the research and tried all of their implementations, but still can't resolve it.
Stack overflow formatting is not working, so:
Axios returning pending promise async/await return Promise { <pending> } Why is my asynchronous function returning Promise { <pending> } instead of a value? Async/await return Promise<pending> https://github.com/Keyang/node-csvtojson/issues/278 https://www.reddit.com/r/Firebase/comments/h90s0u/call_external_api_from_cloud_function/
CodePudding user response:
You are using too many await
in your code.
If you want to use await
on the fetchData
function you should return a Promise
and handle it outside.
Try to change your code like this:
exports.getBitcoinPrice = functions
.region("europe-west1")
.runWith({ timeoutSeconds: 5 })
.https.onRequest(async (req, res) => {
const fetchData = () => {
return axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json", {
timeout: 2000,
})
};
try {
const data = await fetchData();
console.log(await data.json());
} catch (err) {
console.log(error)
}
return null;
});