【发布时间】:2015-03-19 14:53:37
【问题描述】:
好的,我正在寻找一个名为component的列表
一旦结果准备好,我的想法是遍历列表并找到所有question_answer,然后将它们添加到单个对象中。为此,我尝试了以下方法:
Component.findAll({include: [{all: true}], where: {module_id: module_id}}).then(function(components)
{
var i = 0;
for (i = 0; i < components.length; i++) {
if(components[i].dataValues.question_id != null)
{
Question_answer.findAll({where: {question_id: components[i].dataValues.question_id}}).then(function(answers)
{
var i = 0; // here i want to add the value however i cannot reach components[i]
});
}
}
})
.success(onSuccess).error(onError);
我的问题是它是一个内部函数,我无法访问内部函数之外的变量。
所以我的问题是如何在使用多个查询时添加附加值?
【问题讨论】:
-
请澄清您所说的“无法访问组件[i]”是什么意思。 javascript 作用域中的任何内容都不应阻止您这样做。但是,您通过声明
var i来覆盖外部 i,这可能会导致您出现问题吗? -
发生这种情况是因为第二个查询是异步的,当您想使用 component[i] 时,您的 for 循环已经结束。尝试用 forEach 替换 for 循环,这将为每个组件创建一个新函数。但在这种情况下要小心性能问题。
标签: javascript node.js sequelize.js