Search code examples
javascriptnode.jsnode-fetch

JS node-fetch can't get data from a fetch promise


I want to fetch data from the wikipedia api via node-fetch. Unfortunately I don't manage to set a variable outside my fetch-Promise-Chain. I wanted to pass this variable on to render page to fill in a form. If I consle.log the inside the fetch() everything works as I'd expected.

I am new to this and I admit that I don't understand how promises work or how to get practice on this topic.

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

exports.search = (req,res) =>{
  console.log('going to search...' + req.query.eventSearchbar);
  
  let searchterm = req.query.eventSearchbar;
  let wikiDescription = 'Test';
  
  const wikiAPI = "https://en.wikipedia.org/w/api.php";
  let searchURL = new URL(wikiAPI)
  searchURL += "?origin=*&action=query&list=search&srlimit=1&format=json&srprop=snippet&srsearch=";
  searchURL += encodeURIComponent(req.query.eventSearchbar);
  console.log(searchURL);

  fetch(searchURL)
    .then(res => res.json())
    .then(json => json.query.search)
    .then(array => array[0].snippet)
    .then(snippet => {
      wikiDescription  = snippet;
    })
    .catch(err => console.log(err))

  res.render('search',{searchterm: searchterm, wikiDescription: wikiDescription });
}

Solution

  • You need to await the fetch in order for it to work as you expect it to be.

    When your JS code does an Ajax request over the network to get data from the server, you need to set up the response code in a function (which is also called callback).The JS Engine basiclly tells the hosting environment that he is going to suspend the execution for the moment and when the network response arrives back, please let me know and execute that callback function.

    So' in your example, you're making an asynchronous request via fetch. the response will get sometime after you make it but if you won't await that call, the

    res.render('search',{searchterm: searchterm, wikiDescription: wikiDescription });
    

    will surely happen before you get the result back.