为什么readline会卡住?

时间:2018-08-03 14:20:55

标签: javascript node.js readline

这是我的代码,我试图从应该开始要求用户输入的访存中调用一个函数,该函数本身可以正常工作,但是从.then调用它时,它会输出“ Enter Artist”名称:“,当您输入一行并按Enter键时,它不会继续。

function getLyrics(searchTerm) {
  let url = geniusUrl + searchTerm + '-' + 'lyrics';

  fetch(url)
    .then(response => response.text())
    .then(data => {
      const $ = cheerio.load(data);
      lyrics = $('.lyrics').text().trim();
      //styling for console
      if (lyrics) {
        console.log('                    ');
        console.log('####################');
        console.log('                    ');
        console.log(lyrics);
        console.log('                    ');
        console.log('####################');
        console.log('                    ');
      } else if (!lyrics) {
        manualSearch();
      }
    })
    .catch(e => console.log(e));
}

function manualSearch() {
  console.log('Couldn\'t Find Lyrics!');
  console.log('-----Try Manual Search-----');
  getData();
}

function getData() {
  rl.question('Enter Artist Name: ', answer1 => {
    rl.question('Enter Song Name: ', answer2 => {
      if (answer1 != '' && answer2 != '') {
        artistName = answer1.toLowerCase().trim();
        songName = answer2.toLowerCase().trim();
        searchTerm = artistName + songName;
        searchTerm = searchTerm.trim().replace(/in'/g, 'ing').replace(/\W/g, ' ').replace(/n t/g, 'nt').replace(/\s\s+/g, ' ').split(' ').join('-');
        getLyrics(searchTerm);
      } else {
        console.log('Not Valid');
        getData();
      }
    });
  });
  rl.close();
}

更新:

出于某种奇怪的原因,当我将readline-sync而不是节点readline用于“ getData”函数时,它起作用了!

1 个答案:

答案 0 :(得分:2)

因为您要在readline完成之前将其关闭。

您正在做的是

function getData() {
  rl.question('Enter Artist Name: ', answer1 => {
    rl.question('Enter Song Name: ', answer2 => {
      // Your logic........
    });
  });
  rl.close(); // This will close readline
}

您应该做的是:

function getData() {
  rl.question('Enter Artist Name: ', answer1 => {
    rl.question('Enter Song Name: ', answer2 => {
      // Your logic........
      rl.close(); // This will wait until two question asked.
    });
  });
}