在javascript中使用异步函数时,如何保持文件的顺序?

时间:2017-11-30 20:42:36

标签: javascript discord

因此,对于我正在使用的discord bot,我可以创建自定义播放列表,并将其另存为txt文件。我想从文本文件中读取并排队其中的每首歌曲。问题是,这是一个异步功能,所以我失去了秩序,即使我希望它保持秩序,有什么办法可以解决这个问题吗?这就是我的代码看起来像我不知道从哪里开始改变它以使它保持从第一首歌到最后一首的顺序。播放列表文件如下所示:

信徒

意味着

乡村公路带我回家

close remix

对我来说意味着

代码看起来像这样。任何帮助,将不胜感激。谢谢!

      var lineReader = require('readline').createInterface({
        input: require('fs').createReadStream(actualPlaylist)
      });

      lineReader.on('line', async function(line){
        console.log('Line from file:', line);
        url = line ? line.replace(/<(.+)>/i, '$1') : '';
        console.log(url);
        try{
          var aVideo = await youtube.getVideo(url);
        } catch(error) {
          try{
            var myVideos = await youtube.searchVideos(line, 1);
            var aVideo = await youtube.getVideoByID(myVideos[0].id);
          } catch(myError) {
            console.error(myError);
            return msg.channel.send("Couldnt find any videos by that name.");
          }
        }
        return handleVideo(aVideo, msg, voiceChannel, false); // This is a async function we create down below next to the 'play' function!

      });

1 个答案:

答案 0 :(得分:0)

实现这一目标的一种方法是制作一个队列,让它在启动下一个歌曲时将其取消。也许这样的事情。请注意,此代码未经测试。祝你好运!

/* globals youtube msg handleVideo voiceChannel */
var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('./playlist.txt')
})

let songList = []
let called = false

async function getSong (item) {
  let aVideo
  try {
    aVideo = await youtube.getVideo(item.url)
  } catch (error) {
    try {
      const myVideos = await youtube.searchVideos(item.line, 1)
      aVideo = await youtube.getVideoByID(myVideos[0].id)
    } catch (myError) {
      console.error(myError)
      return msg.channel.send('Couldnt find any videos by that name.')
    }
  }
  return handleVideo(aVideo, msg, voiceChannel, false)
}

function videoQueue () {
  if (!songList.length) {
    called = false
    return
  }
  const item = songList.unshift()

  getSong(item)
    .then(() => {
      videoQueue()
    })
    .catch(() => {
      console.log('trying to play next song')
      videoQueue()
    })
}

lineReader.on('line', async function (line) {
  console.log('Line from file:', line)
  const url = line ? line.replace(/<(.+)>/i, '$1') : ''

  songList.push({url, line}) // {url, line} = {url:url, line:line}
  if (!called) videoQueue()
})