了解异步语句的变量作用域

Understanding variable scoping with async statements

本文关键字:变量 作用域 语句 异步 了解      更新时间:2023-09-26

当我执行以下操作时:

for (var CurrentRow=0;CurrentRow < qryMfg.RecordCount;CurrentRow++){
    console.log(qryMfg.MFGID[CurrentRow]);
    dbo.transaction(function(myTrans) {
        console.log(qryMfg.MFGID[CurrentRow]);
    });
}

我按照自己想要的方式得到一个MfgID列表,后面是一个未知列表,因为dbo.transaction是异步执行的。

如何将变量传递到dbo.transaction

变量作用域是在函数中创建的,因此创建一个返回处理程序的函数。。。

function create_handler( scoped_row ) {
    return function(myTrans) {
        console.log(qryMfg.MFGID[scoped_row]);
    };
}

并在循环中调用它,将它传递给任何需要的范围,在本例中,是CurrentRow。。。

for (var CurrentRow=0;CurrentRow < qryMfg.RecordCount;CurrentRow++) {
    console.log(qryMfg.MFGID[CurrentRow]);
    dbo.transaction( create_handler(CurrentRow) );
}

现在,每个单独的处理程序都是在通过每次迭代中的调用创建的相同的唯一作用域中创建的。

由于CurrentRow被传递到该函数作用域,因此每个处理程序都将通过scoped_row参数在其自己的作用域中引用唯一的值。

当处理程序从函数返回时,它将被传递给dbo.transaction

即使它是从创建它的函数中传递出来的,它也将保留其原始变量范围,因此始终可以访问scoped_row参数。


如果您愿意,也可以将整个操作放入函数中。

function create_transaction( scoped_row ) {
    console.log(qryMfg.MFGID[scoped_row]);
    dbo.transaction( function(myTrans) {
        console.log(qryMfg.MFGID[scoped_row]);
    });
}

只要你通过CurrentRow。。。

for (var CurrentRow=0;CurrentRow < qryMfg.RecordCount;CurrentRow++) {
    create_transaction( CurrentRow );
}
for (var CurrentRow=0;CurrentRow < qryMfg.RecordCount;CurrentRow++) {
    console.log(qryMfg.MFGID[CurrentRow]);
    (function(row) {
        dbo.transaction(function(myTrans) {
            console.log(qryMfg.MFGID[row]);
        }); 
    })(CurrentRow);
}