node.js - API built in express responds with empty array -


i have application populating array names. can log array values , getting values, using postman make request on localhost:8888/api/messages response says matches : [] empty array. why array empty in response if 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;         (var = 0; < matches.length; i++){         names.push(matches[i].name);         matches[i].email;       }        res.json({matches : names});      });   });  

this because response.json() executes before ctxioclient.get() happens. call response.json inside .get() instead. 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;       (var = 0; < matches.length; i++) {         names.push(matches[i].name);         matches[i].email;       }       response.json({ matches: names }); // <--- router response     }); }); 

Comments