gpt4 book ai didi

javascript - 在 REST 调用中访问数组

转载 作者:行者123 更新时间:2023-12-03 06:31:25 27 4
gpt4 key购买 nike

我有下面的代码,我在其中声明了数组 var filteredArray = []; 。我使用filteredArray将数据推送到Rest调用的回调函数中(这发生在for循环内)。一旦for循环结束。我想将filteredArray发送到我的 Angular Controller 。这是我的代码。当我将 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({});

});
}

最佳答案

使用异步循环进行异步调用。例如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({});
})
});
}

关于javascript - 在 REST 调用中访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38430631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com