Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save data in variable from HTTP request using Node Fetch?

Im trying to save data from GET request into variable using node-fetch, but i got the some result! When i console log the response, i can see it. But when i assign the resData into variable, i get undefined.

const fetch = require('node-fetch');

async function fetchData(){
const response = await fetch(url, options)
const resData = await response.json();
console.log(resData);
return resData; 
 };
 
let myApps
 
fetchData((data)=>{
 myApps = data;
});
 
console.log(myApps);

result ==> undefined

Someone can help ME!

like image 907
alifnaiech Avatar asked Sep 08 '25 04:09

alifnaiech


1 Answers

Your console.log executes before your network request is completed. This is because HTTP requests are asynchronous. The fetchData method returns a Promise. The correct implementation should be like this:

const fetch = require('node-fetch');

async function fetchData(){
     const response = await fetch(url, options)
     const resData = response.json();
     console.log(resData);
     return resData; 
};
 
let myApps

fetchData().then((data) => {
   // the network request is completed
   myApps = data;
   console.log(myApps);
}).catch((e) => {
   // Network request has failed
   console.log(e);
});

// or using await if your parent method is an `async` function
try {
   myApps = await fetchData()
} catch (e) {
   // Network request has failed
   console.log(e);
}

Update: After the comment of OP

To send a response of fetchData in an API call using express

async function getData(req, res) {
  try {
     const data = await fetchData();
     // you can loop on your data as well
     
     // send the response
     res.json({ data });
  } catch (e) {
     res.status(503).json({ msg: "Internal Server Error" });
  }
}

// somewhere in your route
app.get("/data", getData);

like image 131
Amir Saleem Avatar answered Sep 10 '25 09:09

Amir Saleem