NodeJs: array deletion does not work. And if without a cycle, then it is deleted.
module.exports.run = (client, msg, args) => {
//...
//...
song_search.res.videos.forEach(async (song, i) => {
const songInfoER = await ytdl.getInfo(song.url).catch(err => {
const remove = song_search.res.videos.splice(i, 1); //doesn't work here!
});
});
//...
//..
}
There are a bunch of problems with how you're trying to that. The biggest one is the .forEach()
is not promise-aware or async-aware so the .forEach()
loop runs to completion and then sometime later, in no predictable order, your promises resolve and you try to do .splice()
operations. Since those are done in a random order, they won't have predictable results. In addition, song_search.res.videos
won't have been changed when the .forEach()
loop completes.
There are a number of ways to do this differently. I would suggest a regular for
loop which is promise-aware and async-aware. Since you want to remove items from the array while iterating, it's also easier to iterate the array backwards so removing an item doesn't change the rest of the iteration:
// make the containing function async
const videos = song_search.res.videos;
for (let i = videos.length - 1; i > 0; i--) {
try {
const songInfoER = await ytdl.getInfo(videos[i].url);
// do something with songInfoER here
} catch(e) {
// no info for this video, remove it from the array
videos.splice(i, 1);
}
}
// song_search.res.videos will be updated here