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))
}
Fetch API is an asynchronous web API that comes with native JavaScript, and it returns the data in the form of promises. You use several Web APIs without knowing that they are APIs. One of them is the Fetch API, and it is used for making API requests.
Or as Node. js docs puts it, blocking is when the execution of additional JavaScript in the Node. js process must wait until a non-JavaScript operation completes. Blocking methods execute synchronously while non-blocking methods execute asynchronously.
import fetch from 'node-fetch'; Note: The API between node-fetch 3.0 and 2.0 is the same, just the import differs. As previously mentioned, the fetch() function in the node-fetch module behaves very similarly to the native window. fetch() function.
I think you need to return retrieveLogs function result like this:
async function retrieveLogs(){
return await fetch(url)
.then(res => res.json())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With