Node.js Call A Method After Another Method Is Completed
I would like to call my 'app.get('/news/news-desc', (req, res)' method after 'app.get('/news/api/:newsName', function(req, res)' is completed. Here is my code: As you can see, the
Solution 1:
let articleUrlArray = [];
constaddArticleUrl = url => articleUrlArray.push(url)
constcheckBody = res => (err, response, html) => {
const $ = cheerio.load(html);
const articleContent = $('.article-content').children('p')
const bodyOne = articleContent.eq(0).text()
const bodyTwo = articleContent.eq(1).text()
const isExtensive = bodyOne.split(' ').length > 50res(isExtensive ? { bodyOne } : { bodyOne, bodyTwo })
}
constgetArticle = article => newPromise(res =>request(article, checkBody(res)))
const newsDescMiddleware = app.get('/news/news-desc', (req, res) => {
Promise.all(articleUrlArray.map(getArticle)).then(data => res.send(JSON.stringify(data)))
})
consttechCrunch = res => url =>request(url, (err, response, html) => {
let formattedData = JSON.parse(response.body);
formattedData.articles.forEach(article =>addArticleUrl(article.url))
res(response.body)
})
constgetNewsByName = (newsName, url) => newPromise((res, reject) => ({
'tech-crunch': techCrunch(res)(url)
}[newsName])) || reject()
constgetNewsByNameMiddleware = (req, res) => {
constAPI_KEY = 'example';
const techCrunchURL = `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${API_KEY}`getNewsByName(req.params.newsName, url)
.then(body => {
res.setHeader('Content-Type', 'application/json');
res.send(body)
})
.catch(() => res.send('Please type in correct news source'))
}
app.get('/news/api/:newsName', getNewsByNameMiddleware, newsDescMiddleware)
Here, I made you some middlewares.
I am assuming that you don't need the response of the previous middleware.
I like to split the code by its responsibilities and write it functionally.
Solution 2:
You can separate the core logic of the first route to a function and re-use it in both places, if you please. however you still need to provide newsName parameter to GET '/news/news-desc' endpoint.
Example for your code.
let articleUrlArray = [];
functiongetNewsNames(newsName, callback) {
constAPI_KEY = 'example';
let data = '';
const techCrunchURL = `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${API_KEY}`switch (newsName) {
case'tech-crunch':
request(techCrunchURL, function (err, response, html) {
let formattedData = JSON.parse(response.body);
for (let i = 0; i < formattedData.articles.length; i++) {
articleUrlArray.push(formattedData.articles[i].url);
}
data = response.body;
callback(null, data);
});
break;
default:
data = 'Please type in correct news source';
callback('Error', data);
break;
}
}
app.get('/news/api/:newsName', function (req, res) {
getNewsNames(req,params.newsName, (err, data) => {
if (!err) {
res.setHeader('Content-Type', 'application/json');
}
return res.send(data);
})
})
constcheckBody = res => (err, response, html) => {
const $ = cheerio.load(html);
const articleContent = $('.article-content').children('p')
const bodyOne = articleContent.eq(0).text()
const bodyTwo = articleContent.eq(1).text()
const isExtensive = bodyOne.split(' ').length > 50res(isExtensive ? { bodyOne } : { bodyOne, bodyTwo })
}
constgetArticle = article => newPromise(res =>request(article, checkBody(res)))
app.get('/news/news-desc/:newsName', (req, res) => {
getNewsNames(req.params.newsName, (err, data) => {
// by now, the articleUrlArray array will be filledPromise.all(articleUrlArray.map(getArticle)).then(data => res.send(JSON.stringify(data)))
})
})
Post a Comment for "Node.js Call A Method After Another Method Is Completed"