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