我在下面的代码中声明了数组var filteredArray = [];
。我使用filteredArray来推送Rest调用的回调函数中的数据(这发生在for循环中)。
一旦for循环结束。我想将filteredArray发送到我的角度控制器。这是我的代码。当我把console.log(filteredArray)放在for循环之外时,我得到一个空数组。有人可以帮忙吗?
assignedToMe: function(req, res) {
CustomerUser.find({
userEmail: {
$in: req.body.userEmail
}
}, function(err, docs) {
var filteredArray = [];
for (var i = 0; i < docs.length; i++) {
var url = config.pythiaApi + config.pythiaApiPrefix + '/quotes/' + docs[i]['quoteId'];
if (req.originalUrl.lastIndexOf('?') !== -1) {
url += req.originalUrl.substr(req.originalUrl.lastIndexOf('?'));
}
restClient.get(url, function(body, response) {
filteredArray.push(body.data)
})
}
console.log(filteredArray) // Gives empty array
res.status(200).json({});
});
}
答案 0 :(得分:1)
对异步调用使用异步循环。例如async.times
assignedToMe: function(req, res) {
CustomerUser.find({
userEmail: {$in: req.body.userEmail}
}, function(err, docs) {
var filteredArray = [];
async.times(docs.length, function(i, next){
if(err) return next(err);
var url = config.pythiaApi + config.pythiaApiPrefix + '/quotes/'+docs[i]['quoteId'];
if (req.originalUrl.lastIndexOf('?') !== -1) {
url += req.originalUrl.substr(req.originalUrl.lastIndexOf('?'));
}
restClient.get(url, function (body, response) {
next(null, body.data)
})
}, function(err, result){
// result contains your array
res.status(200).json({});
})
});
}