3

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!

alifnaiech
  • 77
  • 9
  • 2
    `const myApps = await fetchData();` remember to execute it in an async method as well to use `await`. – Getter Jetter Jun 18 '21 at 10:39
  • fetchData is executing asynchronously , and your assignment myApps = data; statement execute before result returned. you need to use await here as well – Afzal Ali Jun 18 '21 at 10:40

1 Answers1

2

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

Amir Saleem
  • 2,912
  • 3
  • 21
  • 35
  • Thank you for the response. The problem is i want save the response into variable and make a for loop to get specific data! – alifnaiech Jun 18 '21 at 10:44
  • How do you want to call the fetchData? as soon as the application starts? or on any event? – Amir Saleem Jun 18 '21 at 10:45
  • Using express, i want to get data from fetchData and next i make route of GET using express that return the result of fetchData. For example, data from fetchData is list of apps, i want to make GET request using express return .json() – alifnaiech Jun 18 '21 at 10:52
  • 1
    then call `fetchData` method in your `controller`. like `async function(req, res) { data = await fetchData() res.json({ data ); }` – Amir Saleem Jun 18 '21 at 10:58
  • this is my Linkedin account ==> https://www.linkedin.com/in/alifnaiech/ so if i get stuck i can contact you – alifnaiech Jun 18 '21 at 13:43
  • Hey All, I have a question about the original question... I see `console.log(myApps);` at the end of code, so I assume alifnaiech wanted to be able to use it globally and tested this by trying to `console.log(myApps);`, and as we learned, the result is undefined. But then in the answer we see async await being used... is there truly no way to simply allow the variable with data myApps to be used in the way that alifnaiech first posed? In other words, is there a way to have myApps be this global piece of data that can be used anywhere outside of async await or functions? – Redink May 29 '23 at 16:29
  • 1
    @Redink yes you can achieve the same. In your server, you can run some asynchronous code and assign the value to the global variables and then call app.listen to start the server so when the server starts you can assure that all the async calls are resolved. – Amir Saleem May 30 '23 at 04:48
  • Thanks Amir Saleem, can you point me to an example of this or share what this looks like? Or is this what you provided in the Update version of your answer? – Redink May 30 '23 at 18:43
  • @Redink I can provide you with an example. Let me know in detail about our problem, do you want to achieve this in front-end or backend?, how are you getting the data? etc. You can mail me at developer.amirsaleem@gmail.com – Amir Saleem May 31 '23 at 13:50