从回调nodejs返回连接的字符串

时间:2014-05-30 01:24:24

标签: javascript string node.js scrape

您好我是nodejs的新手,我在从metrolyrics.com返回一串歌词时遇到了麻烦。歌词存储在单独的段落中,我试图返回一个连接所有段落的字符串。我在线查看了一些资源,看到我必须使用回调函数,但我不认为我正在做正确的事。这是我到目前为止的代码:

var request = require('request');
var cheerio = require('cheerio');

function getLyrics(artistName, songTitle, fn) {
    var lyric = "";
    var url = 'http://www.metrolyrics.com/' + songTitle.toLowerCase().replace(/ /g, "-")+ "-lyrics-" + artistName.toLowerCase().replace(/ /g, "-") + ".html";
    request(url, function(err, resp, body){
        if(err) {
            throw err;
        }
        $ = cheerio.load(body);
        $('#lyrics-body-text p').each(function(){
            lyric += $(this).text();
        });
    }); 
    return fn(lyric);
}

getLyrics('John Legend', 'All of Me', function(result) {console.log(result)});

1 个答案:

答案 0 :(得分:0)

var request = require('request');
var cheerio = require('cheerio');

function getLyrics(artistName, songTitle, fn) {
    var lyric = "";
    var url = 'http://www.metrolyrics.com/' + songTitle.toLowerCase().replace(/ /g, "-")+ "-lyrics-" + artistName.toLowerCase().replace(/ /g, "-") + ".html";
    request(url, function(err, resp, body){
        if(err) {
            throw err;
        }
        $ = cheerio.load(body);
        $('#lyrics-body-text p').each(function(){
            lyric += $(this).text();
        });
        return fn(lyric); // You should call your callback inside request callback, because it's an async operation
    }); 
}

getLyrics('John Legend', 'All of Me', function(result) {console.log(result)});

否则,在请求完成并执行其回调之前,会立即执行return。