Search code examples
node.jsresthttprequestnode-fetch

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!


Solution

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