0

When returning the JSON object items_json, using the express method res.json(items_json), I have run into an issue. When the express method res.json(items_json) is called at POSITION #1 in the code below, the function works perfectly. However, when res.json(items_json) is called at POSITION #2 instead of #1, the JSON object returned is empty:

{
  "example_key_object": []
}

I want to have res.json(items_json) in POSITION #2 so I can add a loop. Why is the JSON response empty when in POSITION #2 but works fine when in POSITION #1? (Context for code below: res.json(items_json) is never in both POSITION #1 & #2)

app.get('/example_apiurl', function(req, res) {

   var items_json = {}
   var key_object = 'example_key_object';
   items_json[example_key_object] = [];

   var item_str; 
   var data;      
   var url = "example.com";

     request(url, function(error, response, html){
        if(!error){
          var $ = cheerio.load(html);

          /*
            some irreverent logic to get var items_clean_st
          */

          item_str = items_clean_st.substring(x,y);
          data = {
            locationID: 2,
            item: item_str
          };
          items_json[key_object].push(data);
          res.json(items_json) //POSITION #1 //returns correctly!
        }
     })
   res.json(items_json) //POSITION #2 //empty :(
  }
})
mr_michael
  • 18
  • 3

1 Answers1

0

You are passing an anonymous function as a parameter to another function called request. I don't know exactly what happens with this anonymous function, but I'm guessing that it is called at a future time in response to some browser event, such as an AJAX request completing.

Therefore, it is likely that the call at POSITION #2 happens before the call at POSITION #1.

Vivian River
  • 31,198
  • 62
  • 198
  • 313