Reputation: 3349
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});
});
});
Upvotes: 0
Views: 467
Reputation: 33618
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
});
});
Upvotes: 2