我有一個對我來說毫無意義的異步/等待問題(我知道,我知道)。我將兩個函式(子函式和 HOF)宣告為異步函式,并在嘗試控制臺記錄它們之前等待回傳的結果。驚喜驚喜,我待定。該函式掛起 60 秒并超時(所以似乎我的runWith超時方法也不起作用。還嘗試在宣告之前記錄一個簡單的“here” 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 回傳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/
uj5u.com熱心網友回復:
您await在代碼中使用了太多。
如果你想await在fetchData函式上使用你應該回傳 aPromise并在外面處理它。
嘗試像這樣更改您的代碼:
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;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/327516.html
標籤:javascript 节点.js 火力基地 异步 异步等待
上一篇:Typescriptimportmodule.exports子函式
下一篇:NpmStart導致無法識別睡眠
