我试图通过循环播放专辑中的歌曲列表,查找相关歌曲并尝试保存到阵列中供以后使用,将一些对象保存到数组中 . 有没有办法实现这个目标?
我需要一些使用猫鼬的解释 .
exports.playlistPlayer = function (req, res, next) {
Playlist.findById({
_id: req.body.playlist._id
}, (err, playlist) => {
var customAlbum = []; //This variable it's inside the same block i believe
playlist.songs.forEach(function (song) {
Song.findById({
_id: song.song_id
}, (err, songs) => {
var customSong = {
title: songs.title,
time: songs.time,
source: songs.source,
song_id: songs._id
}
customAlbum.push(customSong)
console.log(customAlbum) //it works here
});
});
console.log(customAlbum) //it returns an empty array here where i need the data
});
};
1 回答
问题是
findById
方法也是异步的 . 我建议你在javascript中学习promises . 一种可能的解决方案是使用ES7的async / await功能: