asynchronous – 传递variables和保存上下文
如果您有以下代码:
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);
- 如何将variables
a
和b
的值传递给func
以便在for
循环之后执行async.auto(asyncConfig)
时,保留a
和b
的上下文?
(每次执行func
a
和b
不同上下文)
先谢谢你 !
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);
使用绑定的可能替代:
var asyncConfig = {}; var a, b; for(var i = 0; i < someValue; i++) { // do something with a // do something with b asyncConfig[i] = func.bind(asyncConfig, a, b); } // Include some more parallel or series functions to asyncConfig async.auto(asyncConfig);
确保检查您使用此支持的环境是否绑定。 另外,我将“this”值绑定到asyncConfig
,这可能不适合你。
编辑:再次阅读这个问题,是a和b原语或对象/数组? 如果它们不是原始的,那么你就要克隆它们。
- 避免与asynchronouscallback地狱,使用其他模块的function
- 在expressjsasynchronous瀑布处理错误
- Express与asynchronous的Node.js API:遇到多个请求时出错
- http.createserver与node.js中的net.createserver
- Node.js承诺和asynchronousexception
- 在Node.js中运行asynchronous进程
- 使用forEach时,与node.jsasynchronousstream程混淆。
- queue.drain上的node.jsasynchronouscallback错误
- 嵌套在async.eachSeries循环中的async.series会尽早终止发送POST响应