javascript - 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))
}
解决方案
我认为您需要像这样返回retrieveLogs 函数结果:
async function retrieveLogs(){
return await fetch(url)
.then(res => res.json())
}
推荐阅读
- javascript - 如何在 HTML5 Canvas 中禁用形状抗锯齿?(imageSmoothingEnabled 和像素化不起作用)
- javascript - 尝试制作带有控件的 3D 立方体
- algorithm - 自适应采样函数的算法
- bigtable - 如果所有值都被垃圾收集,是否会自动删除一行?
- bash - 从不同路径批量重命名多个文件
- java - 如何在 Java 中创建 SOAP Web 服务,它连接到 Oracle 存储过程并将结果作为 Web 服务响应返回
- go - ...interface{} 函数参数中的“取消引用”元素
- ruby-on-rails - Rails 5:发布路线不适用于根网址
- javascript - 如何替换字符串中的最后一个字符,JS
- android - 使用 FirebaseRecyclerOptions 检索数据