我的应用程序使用名称填充数组。我可以记录数组值并获取值,但是使用邮递员在localhost:8888/api/messages
上发出请求,我的响应显示matches : []
空数组。如果我确实填充它,为什么我的数组在响应中为空?
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});
});
});
答案 0 :(得分:2)
这是因为response.json()
在ctxioclient.get()
发生之前执行。在.get()中调用response.json。像这样的东西
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
});
});