Javascript node-fetch synchronous fetch

Wallace Alley picture Wallace Alley · Sep 3, 2018 · Viewed 14.5k times · Source

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

Answer

Ali Torki picture Ali Torki · Sep 3, 2018

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

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