I'm trying to use node-fetch with nodejs to make api calls to my personal api. I would like to be able to update certain values synchronously within this periodically as things update/change with my database behind the scenes. I know that async and await exist but with all my googling I still don't quite understand them or how they interact with fetch requests.
This is a bit of example code I'm trying to get working but still just logs undefined
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))
}
await example();.then(json => {return json})this line is pointless. Just remove it.asyncandawaitdoes not make your action synchronous. It is just syntaxic sugar to make your code more elegant and display it like if it was synchronous. Actions are still asynchrnous behind the scene.