[英]Javascript node-fetch synchronous fetch
我正在嘗試使用 node-fetch 和 nodejs 對我的個人 api 進行 api 調用。 我希望能夠在此期間同步更新某些值,因為我的數據庫在幕后更新/更改。 我知道 async 和 await 存在,但是通過我所有的谷歌搜索,我仍然不太了解它們或它們如何與 fetch 請求交互。
這是我正在嘗試工作的一些示例代碼,但仍然只是未定義的日志
const fetch = require('node-fetch');
const url = 'http://example.com';
let logs;
example();
console.log(logs);
async function example(){
//Do things here
logs = await retrieveLogs();
//Do more things here
}
async function retrieveLogs(){
await fetch(url)
.then(res => res.json())
.then(json => {return json})
.catch(e => console.log(e))
}
我認為您需要像這樣返回retrieveLogs 函數結果:
async function retrieveLogs(){
return await fetch(url)
.then(res => res.json())
}
正如 Ali Torki 在評論中所說, fetch()
是一個異步函數,無論如何都不能“進行”同步。 如果您必須與 HTTP 同步獲取(例如,因為您必須在不能是異步的屬性 getter 中使用它),那么您必須使用不同的 HTTP 客戶端,句號。
npm install sync-fetch
圍繞 Fetch API 的同步包裝器。 在幕后使用節點獲取,也用於一些輸入解析代碼和測試用例。
使用立即調用的異步函數表達式:
(async () => {
try {
const response = await fetch('http://example.com')
const json = await response.json()
} catch (error) {
console.log(error);
}
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.