0

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/

crevulus
  • 1,658
  • 12
  • 42

1 Answers1

1

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(data);
      } catch (err) {
          console.log(err)
      }
      return null;
    });
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
  • Thank you so much @luca . This is the correct answer, with two sidenotes: 1. In axios, we don't use `data.json()` (I've jsut learned). in the `fetchData` fn, I had to append a `.then(response => response.data)`. 2. Typo in the catch block; change to `catch (error)`. – crevulus Oct 20 '21 at 12:50
  • @crevulus Fixed both in the answer, thank you for pointing those out! – lpizzinidev Oct 21 '21 at 06:52