所以这是我的代码,我试图从 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/