Javascript node-fetch synchronous fetch

Viewed 22753

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

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

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

As Ali Torki said in comment, fetch() is an async function and cannot be "made" sync no matter what. If you MUST fetch synchronously with HTTP (e.g. because you MUST use it in a property getter which MUSTN'T be async), then you MUST use a different HTTP client, full stop.

Using Immediately Invoked Async Function Expression:

(async () => {
  try {

    const response = await fetch('http://example.com')
    const json = await response.json()

  } catch (error) {
    console.log(error);
  }
})();
Related