NodeJS – 如何使forEach和for循环函数顺序

server.queue.forEach(function(q) { YTDL.getInfo(q, (error, info) => { console.log(info["title"]); message.reply('"' + info["title"] + '"'); }); }); for (var i = 0; i < server.queue.length; i++) { YTDL.getInfo(server.queue[i], (error, info) => { console.log(info["title"]); message.reply('"' + info["title"] + '"'); }); } 

我使用Node.js创build了一个名为Discord的VoIP音乐机器人,每当上述任一循环执行时,都会以随机顺序打印。 如何使它们按顺序打印(server.queue [0],server.queue [1],server.queue [2] …)? YTDL是一个名为ytdl-core的软件包,用于下载YouTubevideo,并使用video链接显示video标题等信息。 server.queue是一组YouTubevideo链接。

只是:

1)安装: npm i --save async

2)和代码:

 const async = require('async'); async.eachSeries( server.queue, (q, next) => { YTDL.getInfo(q, (error, info) => { console.log(info["title"]); message.reply('"' + info["title"] + '"'); next(); }); } }); 

for..loop对于asynchronous的东西并不是很好的解决scheme – 它会调用它们并运行for循环之后的下一个语句

如果你不想使用async库,你可以像这样使用Promise.all

 const youtubeData = []; for (var i = 0; i < server.queue.length; i++) { youtubeData.push(YTDL.getInfo(server.queue[i])); } Promise.all(youtubeData).then((values) => { // These values will be in the order in which they are called. }); 

请注意, Promise.all将等待所有查询完成或拒绝一切请求失败。 看看你的用例,并相应地select。

根据库,如果没有提供callback,则返回承诺

ytdl.getInfo(url,[options],[callback(err,info)])

如果您只想从video获取metainfo,请使用此选项。 如果没有给出callback,则返回一个承诺。