【问题标题】:How to return only when my callback is complete [duplicate]仅当我的回调完成时如何返回[重复]
【发布时间】:2014-12-25 10:19:15
【问题描述】:

我正在编写一个 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;

    });
}

【问题讨论】:

    标签: javascript node.js asynchronous callback return


    【解决方案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'});
        });
    });
    

    【讨论】:

    • 太棒了!我将helper.scrapePage 移到app.get 之外,因此每次有人访问'/' 时都不会调用它。非常感谢!
    猜你喜欢
    • 2023-03-28
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2020-12-25
    • 1970-01-01
    • 2012-05-25
    相关资源
    最近更新 更多