I know this topic is covered in many questions. I have read many of them but couldn't translate the information to my situation as there are many frameworks for both Promises and making asynchronous HTTP requests. The more I read, the more confused I get. So I kindly ask for your help on this task. I will try to keep it as specific as possible.
This is what I want to do:
A user enters a search term and by submitting an api call is made to the Wikimedia API, requesting Wikipedia pages for that search term. This results in a list of pages, which can be normal pages or meta pages. I want to filter out the meta pages.
// the first call to the API, requesting the sources(pages)
axios.get(url, {params})
.then(function (res) {
const html = res.data[1].map((source) => {
// here I want to filter meta pages
if (isNotMetaPage(source)) {
return `
<div class='sources_list_entry'>
<p> ${source} </p>
</div>
`
}
}).join('')
In the function isNotMetaPage()
I need to make another API call to Wikipedia, to get the page type (it is not included in the first request) and return true
for a normal page and false
for meta pages.
function isNotMetaPage (title) {
const encodedTitle = encodeURI(title)
const query = `?action=query&titles=${encodedTitle}&prop=revisions&rvprop=content&format=json&origin=*`
let result
axios.get(url.concat(query))
.then(function (response) {
const wikiPage = parseWikiMarkup(response)
result = (wikiPage.type === 'page')
})
return result
}
Obviously, this function returns undefined
, as the request is asynchronous and and result is returned before the API replies. When logging the result to the console inside the then
-block it has the right value.
But how can I pause the execution until I have the result back? I read a lot that I should not make synchronous calls, but how can I avoid it here?
Appreciate your help!