0

I am looking for a little help with trying to execute an http.get() request and update a variable based on the results. Then use that variable as a response to a request for a web page. I understand that node.js is asynchronous so it won't necessarily wait for one function to finish executing before completing another.

What I am essentially trying to accomplish is to simulate getting blog posts from an API via a get request. The get request responds with the posts in JSON format. Then I want to pass that variable to res.render(), which renders blog.ejs and iterates over the posts.

So, I am really just looking for the right technique to implement since the response is rendered before the http.get() request is finished.

app.get('/blog', function(req, res){
 // Get blog posts from WordPress
 var posts = {};

 http.get({
  hostname: 'localhost',
  port: 3000,
  path: '/',
  agent: false
 }, (res)=>{
  posts = [{post:"Post 1"}];
 });

 res.render('blog', {
  title: 'Blog',
  posts: posts
 })
}) //End /blog request
Collin McGuire
  • 714
  • 3
  • 8
  • 14

0 Answers0