Я пишу местное приложение для потоковой передачи музыки с использованием Node и NodeWebkit. В моем приложении я просматриваю папку с музыкой для любых каталогов, загружаю обложку альбома, а затем показываю искусство в html. Однако логика обнаружения конца итераторов .forEach()
в конце каждого асинхронного обратного вызова не делает чистый код с точки зрения разработчиков. Логически это работает, но если бы я должен был распутать эту строку зависимостей, мне пришлось бы переписать все это.Оптимальный способ для хранения асинхронных событий обратного вызова в Nodejs
Вот отрывок из моего кода:
// 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) {' должен работать? – Bergi
Я рекомендую взглянуть на обещания. – Bergi
Вы также смешиваете код браузера с кодом Node.js. – djfdev