javascript - 为什么readline会卡住?

标签 javascript node.js readline

所以这是我的代码,我试图从 fetch 调用一个函数,该函数应该开始询问用户输入,该函数本身单独工作正常,但是当从 .then 调用它时输出“输入艺术家姓名:”,当您输入一行并按 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 而不是 Node readline 来执行“getData”函数时,它起作用了!

最佳答案

因为您要在完成之前关闭 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.
    });
  });
}

关于javascript - 为什么readline会卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51674686/

相关文章:

javascript - 实例 stub 方法

javascript - 带 Jest 的 vue-test-utils 为 map-spread 运算符抛出意外的 token 错误

javascript - 紧邻 html 标签下的 div 标签的合法性

node.js - 如何在 AWS API 网关中调试 "Missing Authentication Token"?

python - 在不重新编译 Python 的情况下添加 Readline 功能

Cygwin "cannot find -lreadline"

bash - 不要与 shell 本身共享从 shell 启动的进程的标准输入

javascript - JS/正则表达式 : Remove a substring from end of string with optional comma and spaces in front and dot behind

javascript - 如何扩展 jquery ui 小部件? (1.7)

node.js - 安装 NODE JS 时出现此错误