如果您具有以下代码:

var asyncConfig = {};
var a, b;
for(var i = 0; i < someValue; i++) {
    // do something with a
    // do something with b
    asyncConfig[i] = function(callback) {
        func(a, b, callback); // func is async
    }
}
// Include some more parallel or series functions to asyncConfig
async.auto(asyncConfig);
  • 如何将ab变量的值传递给func,以便在async.auto(asyncConfig)循环后执行for时,保留ab的上下文?

  • (对于a的每次执行,bfunc的上下文不同。)

    先感谢您 !

    最佳答案

    var asyncConfig = {};
    var a, b;
    for(var i = 0; i < someValue; i++) {
        // do something with a
        // do something with b
        (function(a,b){
          asyncConfig[i] = function(callback) {
            func(a, b, callback); // func is async
          }
        })(a,b);
    }
    // Include some more parallel or series functions to asyncConfig
    async.auto(asyncConfig);
    

    关于javascript - 异步-传递变量和保留上下文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16279034/

    10-09 20:05