1

当我执行以下操作时:

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?

4

2 回答 2

4

变量范围是在函数中创建的,所以创建一个返回处理程序的函数......

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 );
}
于 2012-01-17T20:42:41.593 回答
4
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);
}
于 2012-01-17T20:46:21.083 回答