2014-10-29 61 views
0

我正在寫一個Node.js應用程序,我無法返回我的網頁刮到我的主要app.get函數的值。該頁面被抓取得很好,並且它的結果使我一直回到我的回調中的RETURN,但它實際上並沒有返回值。任何幫助,將不勝感激!如何返回只有當我的回調完成

編輯:這必須是一個純JavaScript的解決方案,不使用jQuery的。

在我server.js文件,我有這樣的代碼:

var machineDetails = helpers.scrapePage(); 

app.get('/', function (req, res) { 

    res.render('index', { machineDetails: machineDetails, title: 'VIP IT Dashboard'}); 
}); 

在helpers.js文件我有以下功能

//Requires 
httpntlm = require('httpntlm'), 
cheerio = require('cheerio'); 


var userData; 

function callSite(callback) { 

    //Scrape site and get information 
    var scrape; 

    httpntlm.get({ 
     url: "http://URLthatIamScraping.com", 
     username: 'username1', 
     password: 'password1', 
     domain: 'companyDomain' 
    }, function (err, res) { 
     if (err) return err; 

     //Sort information for the computer 
     var $ = cheerio.load(res.body); 

     var scrape = $('#assetcontent').html(); 

     //Return the html content of the page 
     callback(scrape); 

    }); 
} 


exports.scrapePage = function(){ 

    return callSite(function(data) { 

     //This is called after HTTP request finishes 
     userData = data; 

     //ISSUE: userData is not actually making it back to my server.js variable called "machineDetails" 
     return userData; 

    }); 
} 

回答

1

它是異步的,你不能只返回值。它必須在回調中返回。

//Requires 
httpntlm = require('httpntlm'), 
cheerio = require('cheerio'); 


function callSite(callback) { 

    httpntlm.get({ 
     url: "http://URLthatIamScraping.com", 
     username: 'username1', 
     password: 'password1', 
     domain: 'companyDomain' 
    }, function (err, res) { 
     if (err) return callback(err); 

     //Sort information for the computer 
     var $ = cheerio.load(res.body); 

     var scrape = $('#assetcontent').html(); 

     //Return the html content of the page 
     callback(null, scrape); 

    }); 
} 


exports.scrapePage = callSite; 

然後你做:

app.get('/', function (req, res, next) { 
    helpers.scrapePage(function(error, machineDetails) { 
     if(error) return next(error); 
     res.render('index', { machineDetails: machineDetails, title: 'VIP IT Dashboard'}); 
    }); 
}); 
+0

好極了!我將'helper.scrapePage'移到了app.get之外,因此每次有人訪問''/''時都不會調用它。非常感謝! – RandomDeduction 2014-10-29 16:17:27