Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript node-fetch synchronous fetch

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))
}
like image 833
Wallace Alley Avatar asked Sep 03 '18 08:09

Wallace Alley


People also ask

Is fetch synchronous or asynchronous?

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.

Does node js support synchronous?

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.

Is node-fetch the same as fetch?

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.


1 Answers

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

async function retrieveLogs(){
    return await fetch(url)
    .then(res => res.json())
}
like image 109
Ali Torki Avatar answered Sep 19 '22 10:09

Ali Torki