Javascript 节点获取同步获取

标签 javascript async-await synchronous node-fetch

我正在尝试使用 node-fetch 和 nodejs 对我的个人 api 进行 api 调用。随着我的数据库在幕后更新/更改,我希望能够在此期间同步更新某些值。我知道 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))
}

最佳答案

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

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

关于Javascript 节点获取同步获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52146053/

相关文章:

javascript - 哪些网络浏览器原生支持 Array.forEach()

javascript - 缓冲音频源

javascript - jQuery Masonry 可以垂直而不是水平定向 div 吗?

asynchronous - Javamail 是异步的还是同步的?

javascript - 异步还是同步?我该如何处理这些API调用?

javascript - 如果输入有值,则应检查特定的单选按钮

c# - 嵌套Task.WhenAll有什么限制吗?

c# - 如何调试卡在 Windows Phone 8.1 上的应用程序

c# - 在控制台或 Web 应用程序中使用 async/await

javascript - 同步与异步 Nodejs