首页 > 解决方案 > Javascript节点获取同步获取

问题描述

我正在尝试将 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))
}

标签: javascriptasync-awaitsynchronousnode-fetch

解决方案


我认为您需要像这样返回retrieveLogs 函数结果:

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

推荐阅读