0

I have my application populating an array with names. I can log the array values and it is getting the values, but using postman to make a request on localhost:8888/api/messages my response says matches : [] with the empty array. Why is my array empty in the response if I do indeed populate it?

router.get('/messages', function(request, res) {

  var names = [];
  ctxioClient.accounts(ID).contacts().get({limit:250, sort_by: "count", sort_order: "desc"}, 
    function ( err, response) {
      if(err) throw err;

      console.log("getting responses...");
      var contacts = response.body;
      var matches = contacts.matches;


      for (var i = 0; i < matches.length; i++){
        names.push(matches[i].name);
        matches[i].email;
      }  

    res.json({matches : names});   
  });


}); 
1
  • 1
    async, async, async. All async results must be processed and used inside the async completion callback, not outside of it. Commented Jul 15, 2015 at 2:27

1 Answer 1

2

This is because the response.json() executes before the ctxioclient.get() happens. Call response.json inside .get() instead. Something like this

router.get('/messages', function(request, response) { // <--- router response
  var names = [];
  ctxioClient.accounts(ID).contacts().get({ limit: 250,sort_by: "count",sort_order: "desc"},function(err, resp) { // <---- using resp
      if (err) throw err;
      console.log("getting responses...");
      var contacts = response.body; 
      var matches = contacts.matches;
      for (var i = 0; i < matches.length; i++) {
        names.push(matches[i].name);
        matches[i].email;
      }
      response.json({ matches: names }); // <--- router response
    });
});
Sign up to request clarification or add additional context in comments.

9 Comments

I'm putting it where you stated, but I then get the error response.json has no method json
the function inside .get also have the variable response. I just saw that. rename it to something else
Ok actually i'm assuming this is because I pass two parameters in as response and it is trying with the ctxClient response and not the get reponse
yes, true. Please check my updated answer. You'll see that the callback function for ctxioclient.get will have a parameter resp instead of response
I fixed it, and now I get no error, but my array is still empty. I've updated my code to reflect my changes
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.