Reputation: 51
So here is my code, I'm trying to call a function from fetch that should begin asking the user for input, the function itself works fine alone, but when calling it from .then
it outputs "Enter Artist Name: " and when you enter a line and hit enter, it doesn't go on.
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();
}
UPDATE:
For some odd reason when I used readline-sync
instead of node readline
for the "getData" function, It worked!
Upvotes: 0
Views: 409
Reputation: 4200
Because you are closing readline
before it gets completed.
What you are doing is:
function getData() {
rl.question('Enter Artist Name: ', answer1 => {
rl.question('Enter Song Name: ', answer2 => {
// Your logic........
});
});
rl.close(); // This will close readline
}
And what you should do is:
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.
});
});
}
Upvotes: 2