在nodejs / async中提升的JavaScript变量 [英] JavaScript variables hoisting in nodejs/async
问题描述
在下一个示例中,我无法访问函数fetcher,parser和saveToDb中的变量locals。
var parser = require('parser.js');
var fetcher = require('fetcher.js');
var saveToDb = require('models/model.js');
var async = require('async');
function task() {
var locals = [] //<-- declared here
async.series([
fetcher, //<-- can not access "locals"
parser, //<-- can not access "locals"
saveToDb //<-- can not access "locals"
],
function (err) {
if (err) return callback(err);
callback(null);
});
}
在下一个示例中local可以访问。我只是从请求的模块中复制了函数声明,并将它们直接粘贴到async.series中。
In the next example "local"s is accessible. I just copyed the functions declarations from the requested modules, and pasted them straight inside "async.series".
var async = require('async');
function task() {
var locals = [] //<-- declared here
async.series([
function(callback) {// <-- can access "locals"},
function(callback) {// <-- can access "locals"},
function(callback) {// <-- can access "locals"}
],
function (err) {
if (err) return callback(err);
callback(null);
});
}
虽然这有效但我确实希望保持我的代码模块化。
如何解决这个问题? 或 - 我在这里忘记了JavaScript的基础知识?
While this works - I do want to keep my code modular. How can I fix that ? Or - what I forgot here about the fundamentals of JavaScript ?
谢谢。
推荐答案
在第一个例子中,回调直播在另一个范围内,因此无法访问本地人
。
In the first example, the callbacks live in another scope so can't access locals
.
您可以创建获得<$ c $的部分函数c> locals 作为第一个参数传递的变量,但这需要你重写你的回调。
You could create partial functions that get the locals
variable passed as first argument, but that would require you to rewrite your callbacks.
// creating a partial
async.series([
fetcher.bind(fetcher, locals),
parser.bind(parser, locals),
saveToDb.bind(saveToDb, locals)
], ...)
// new function signatures
function fetcher (locals, callback) { ... }
function parser (locals, callback) { ... }
function saveToDb(locals, callback) { ... }
这篇关于在nodejs / async中提升的JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!