Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  44] [ 6]  / answers: 1 / hits: 25741  / 6 Years ago, mon, september 3, 2018, 12:00:00

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))
}

More From » async-await

 Answers
17

I think you need to return retrieveLogs function result like this:



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

[#53574] Thursday, August 30, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
earllutherf

Total Points: 412
Total Questions: 108
Total Answers: 102

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;