为什么没有在 NodeJS 中删除特定数组?

Why isn't a specific array being deleted in NodeJS?

NodeJs:数组删除不起作用。如果没有循环,则删除。

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!
    });
});
//...
//..
}

您的尝试存在很多问题。最大的一个是 .forEach() 不是 promise-aware 或 async-aware 所以 .forEach() 循环运行到完成,然后在一段时间后,以不可预测的顺序,你的承诺解决了,你尝试做 .splice() 操作。由于这些是按随机顺序完成的,因此不会有可预测的结果。此外,当 .forEach() 循环完成时,song_search.res.videos 不会被更改。

有很多不同的方法可以做到这一点。我建议使用常规 for 循环,即 promise-aware 和 async-aware。由于您想在迭代时从数组中删除项目,因此向后迭代数组也更容易,因此删除项目不会改变迭代的其余部分:

// 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