我正在尝试使用 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/