【问题标题】:Axios in a firebase function returning pending promise even inside two async/await blocks即使在两个 async/await 块内,firebase 函数中的 Axios 也会返回待处理的 Promise
【发布时间】:2021-12-07 04:51:29
【问题描述】:

我有一个对我来说毫无意义的异步/等待问题(我知道,我知道)。我将两个函数(子函数和 HOF)声明为异步,并在尝试控制台记录它们之前等待返回的结果。惊喜惊喜,我待定。该函数挂起 60 秒并超时(所以似乎我的 runWith 超时方法也不起作用。还尝试在声明 const fetchData 之前记录一个简单的“此处”,但也没有记录。但控制台在实际调用 fn 后进行日志记录...

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;
    });

我想使用 fetch,但显然 node-fetch 不适用于 firebase。

我将尝试提供我读过的关于 async/await 的许多 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/

【问题讨论】:

    标签: javascript node.js firebase asynchronous async-await


    【解决方案1】:

    您在代码中使用了太多await
    如果你想在fetchData 函数上使用await,你应该返回一个Promise 并在外面处理它。

    尝试像这样更改您的代码:

    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;
        });
    

    【讨论】:

    • 非常感谢@luca。这是正确的答案,有两个旁注:1.在axios中,我们不使用data.json()(我已经学会了)。在fetchData fn 中,我必须附加一个.then(response =&gt; response.data)。 2. catch 块中的错字;更改为catch (error)
    • @crevulus 在答案中都已修复,感谢您指出!
    猜你喜欢
    • 2018-03-27
    • 2020-09-22
    • 1970-01-01
    • 2021-08-06
    • 2022-01-22
    • 2019-01-27
    • 2019-03-31
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多