Javascript 节点获取同步获取

Javascript node-fetch synchronous fetch

我正在尝试使用 node-fetch 和 nodejs 来 api 调用我的个人 api。我希望能够在幕后使用我的数据库作为 update/change 定期同步更新某些值。我知道 async 和 await 存在,但通过我所有的谷歌搜索,我仍然不太了解它们或它们如何与获取请求交互。

这是一些示例代码,我正在尝试开始工作,但仍然只记录未定义的日志

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

我认为您需要 return retrieveLogs 函数结果如下:

async function retrieveLogs(){
    return await fetch(url)
    .then(res => res.json())
}

正如 Ali Torki 在评论中所说,fetch() 是一个异步函数,无论如何都不能 "made" 同步。如果您必须使用 HTTP 同步获取(例如,因为您必须在 属性 getter 中使用它,而不能是异步的),那么您必须使用不同的 HTTP 客户端,句号。

使用立即调用的异步函数表达式:

(async () => {
  try {

    const response = await fetch('http://example.com')
    const json = await response.json()

  } catch (error) {
    console.log(error);
  }
})();
npm install sync-fetch

Fetch 周围的同步包装器 API。在引擎盖下使用节点获取,也用于一些输入解析代码和测试用例。

https://www.npmjs.com/package/sync-fetch