[英]Axios in a firebase function returning pending promise even inside two async/await blocks
我有一个对我来说毫无意义的异步/等待问题(我知道,我知道)。 我将两个函数(子函数和 HOF)声明为异步函数,并在尝试控制台记录它们之前等待返回的结果。 惊喜惊喜,我待定。 该函数挂起 60 秒并超时(所以似乎我的runWith
timeout 方法也不起作用。还尝试在声明const fetchData
之前记录一个简单的“here”,但也没有记录。但实际之后的控制台日志记录调用 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 返回pending promise async/await return Promise { <pending> } 为什么我的异步函数返回Promise { <pending> } 而不是一个值? 异步/等待返回承诺<pending> https://github.com/Keyang/node-csvtojson/issues/278 https://www.reddit.com/r/Firebase/comments/h90s0u/call_external_api_from_cloud_function/
您在代码中使用了太多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(await data.json());
} catch (err) {
console.log(error)
}
return null;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.