【发布时间】:2016-05-05 19:42:16
【问题描述】:
我正在使用 Node 和 NodeWebkit 编写一个本地音乐流媒体应用程序。在我的应用程序中,我扫描音乐文件夹中的任何目录,加载专辑封面,然后以 html 显示艺术。但是,从开发人员的角度来看,在每个异步回调结束时检测 .forEach() 迭代器结束的逻辑并不能生成干净的代码。从逻辑上讲它是可行的,但如果我要解开这串依赖关系,我就必须全部重写。
这是我的代码的 sn-p:
// Fetch the music albums
fs.readdir("./music", function(err, files) {
if (err) {
//return console.error(err);
}
//document.write(JSON.stringify(files));
// Look specifically for music album folders (directories)
filterDirectories("./music", files, function(dirs){
dirs.forEach(function(dir, index, array){
fs.readFile('./music/' + dir + "/album.json", 'utf-8', function (err, data) {
data = JSON.parse(data);
if (err) {
return console.error(err);
}
// Create a li item for every album, and append it to the unordered list
var li = $('<li><img /><a target="_blank"></a></li>');
li.find('a')
.attr('href', '#')
.text(data.album_name);
li.find('img').attr('src', './music/' + dir + '/' + data.album_art_loc).css('width:512px;height:512px;');
lis.push(li);
// Is this the last album folder?
if(index == array.length-1) {
// Go through the array
lis.forEach(function(item, index, array){
// add to the ul element
item.appendTo(ul);
// Have we added the last one to the ul element?
if(index == array.length - 1){
// Ok, now we initialize the flipster plugin to make it look 3D and advanced
$('.flipster').flipster({
style: 'carousel'
});
}
});
}
});
});
});
});
【问题讨论】:
-
lis在哪里初始化?if(index == array.length-1) {应该如何工作? -
我推荐看看promises。
-
您还将浏览器代码与 Node.js 代码混合在一起。
-
@djfdev NWjs @Bergi lis 在应用程序顶部进一步初始化。
lis = [];。当索引计数器到达列表中的最后一个元素时,我们知道我们已经获取了与该专辑有关的所有信息。但是我发现这并不总是正确的,因为它是异步的。
标签: javascript node.js asynchronous node-webkit asynccallback