我正在完成一些教程,无法理解为什么这行“self.only_dirs.push(files [i]);”引起关于它'未定义'的错误。这必须是一个可变范围的问题,但我尝试过的任何工作都没有。怎么办我需要声明变量,以便这些嵌入式回调函数识别它们?
function load_album_list(callback, callback2)
{
var self = this;
fs.readdir
(
'albums',
function (err, files)
{
if(err)
{
callback(err, null);
return;
}
var only_dirs = [];
var remaining = files.length;
for (var i = 0; i < files.length; i++)
{
fs.stat("albums/" + files[i],
function(err, stats)
{
if(stats.isDirectory())
{
self.only_dirs.push(files[i]);
}
console.log("remaining: " + self.remaining);
self.remaining -= 1;
if (self.remaining == 0)
callback(null, self.only_dirs);
}
);
}
callback(null, only_dirs);
}
);
}
答案 0 :(得分:2)
function load_album_list(callback, callback2)
{
var self = this;
self.only_dirs = []; //<----- declare only_dirs in this scope
fs.readdir
(
'albums',
function (err, files)
{
if(err)
{
callback(err, null);
return;
}
//var only_dirs = []; <--- remove this reference
var remaining = files.length;
for (var i = 0; i < files.length; i++)
{
fs.stat("albums/" + files[i],
function(err, stats)
{
if(stats.isDirectory())
{
self.only_dirs.push(files[i]);
}
console.log("remaining: " + self.remaining);
self.remaining -= 1;
if (self.remaining == 0)
callback(null, self.only_dirs);
}
);
}
callback(null, self.only_dirs);
}
);
}