gpt4 book ai didi

node.js - 在 Node.js 中处理循环内的查询

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:35 26 4
gpt4 key购买 nike

在下面的代码中,由于异步行为,val变量值不断变化并生成意外的输出,即在第一个循环的连接查询完成之前,var变量根据第二个循环并生成错误的输出。处理的最佳方法是什么循环中的查询可以避免异步性质引起的特殊情况。

    var output = [];
for ( var j = 0; j < someArr.length ; j++ ) {
val = someArr[j];//some manipulation of someArr[j]
connection.query( "select id from someTable where someCol = ?",val, function(err, rows, fields) {
if ( err ) {
console.log( err );
} else {
output.push( rows[0].someVal );//push query output to this variable
}
});
}

console.log(output);//应该包含所有查询的输出。

最佳答案

只需使用闭包来生成临时作用域

var output;
for ( var j = 0; j < someArr.length ; j++ ) {
tVal = someArr[j];//some manipulation of someArr[j]
(function(val){
connection.query( "select id from someTable where someCol = ?",val, function(err, rows, fields) {
if ( err ) {
console.log( err );
} else {
output.push( rows[0].someVal );//push query output to this variable
}
});
})(tVal);
}

理论

执行上下文

JavaScript 是一种单线程语言,这意味着一次只能执行一个任务。当 JavaScript 解释器最初执行代码时,默认情况下它首先进入全局执行上下文。从此时起,每次调用函数都会创建一个新的执行上下文。

作用域链

对于每个执行上下文,都有一个与其耦合的作用域链。作用域链包含执行堆栈中每个执行上下文的变量对象。它用于确定变量访问和标识符解析。

说明

匿名函数帮助我们创建一个新的作用域“阻止” tVal 的值因为什么时候执行一个新的 scope添加到 scope chain包含val值(value)。这个新scope父级子级 scope其中for loop当循环继续tVal时执行改变但是val包含在 scope 中并且不会受到变异的影响。

关于node.js - 在 Node.js 中处理循环内的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891317/

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