我有一个带有查询字符串的对象数组。我根据关键字循环查询。查询正在按预期方式工作。但是关键不是在里面打印
query = {
A: { code: { '$in': ['A'] }},
B: { code: { '$in': ['B'] }}
}
for (keyQuery of Object.keys(query)) {
console.log("outside",keyQuery );
testcollection
.find(query[keyQuery],{_id:0})
.then(data => {
console.log("inside",keyQuery);
});
}
当前输出为
outside A
outside B
inside B
inside B
预期输出为
outside A
outside B
inside A
inside B
我在做什么错
答案 0 :(得分:2)
最可能的问题原因是var
关键字。使用关键字keyQuery
定义let
,以使其成为块作用域。
for (let keyQuery of Object.keys(query)) {
// code
}
如果在使用变量之前未声明keyQuery
,它将使用var
关键字进行全局声明。
const testCollection = {
find() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(2), 2000);
});
}
}
const query = {
A: { code: { '$in': ['A'] }},
B: { code: { '$in': ['B'] }}
}
for (let keyQuery of Object.keys(query)) {
console.log("outside",keyQuery );
testCollection
.find()
.then(data => {
console.log("inside",keyQuery);
});
}