在请求内部等待请求完成

Waiting for a request to finish inside a request

本文关键字:请求 内部 等待      更新时间:2023-09-26

我有一个代码,从另一个网站请求数据(获取链接),我获取链接后,我会从这些链接获取一些数据。所以,我试着做2个请求。

下面是我编写的伪代码。

[first request to the site]
..fetch links and data
....fetch more data from the fetched links
[done]
[another function to fetch data from the links fetched]
..fetch data
[return fetch data]

我试图得到这样的输出:

{
    "chimchar" : {
        "articles" : [{
            "id": id,
            "title": title,
            "url": url
        }]
    }
}

但是'url'的值没有显示,我尝试将其登录到控制台,'url'的值未定义,并且在从. gethome函数发出所有请求后显示。

下面是代码

var cheerio = require('cheerio');
var requestify = require('requestify');
var _response;
/*
getHome
*/
exports.getHome = function(req, res) {
    requestify.get('http://chimchar.com').then(function(response) {
        var __response = processResponse(response);
        res.send(__response);
    });
}
/*
processResponse
*/
function processResponse(response) {
    var id = 0;
    var title, url;
    _response = {
        'chimchar': {
            'articles': []
        }
    };
    response.getBody();
    $ = cheerio.load(response.body);
    $('#scenesContainer .video_box').each(function() {
        $(this).find('img, a').each(function(i, elem) {
            if ($(this).is('img') && $(this).attr('style') == 'margin-top: 35px;')
                title = $(this).attr('alt');
            if ($(this).is('a') && $(this).attr('class') == 'link_block') {
                fetchPage($(this).attr('href'), function(returnValue) {
                    url = returnValue;
                    console.log(url);
                });
            }
        });
        _response.chimchar.articles.push({
            "id": id,
            "title": title,
            "url": url,
        });
        id = id + 1;
    });
    return _response;
}
var fetchPage = function(page, callback) {
    console.log('fetchPage');
    requestify.get('http://chimchar.com' + page).then(function(response) {
        var r;
        response.getBody();
        $ = cheerio.load(response.body);
        $('.play_video').each(function() {
            $(this).find('a').each(function(i, elem) {
                if ($(this).is('a') && $(this).text().indexOf('MP4') > -1) {
                    r = $(this).attr('href');
                    console.log(r);
                }
            });
        });
        console('fetchPage finished - ' + r);
        callback(r);
    });
};

我想

return _response;

触发,然后urlprocessResponse函数

中获得

我认为你需要使用async,代码看起来像这样

function processResponse(response, callback) {
    async.each([items], function (item, cb) {
        doSomething(item, function () {
            //Make all operations with response
            cb(null, true)
        });
    },
    function (err, result) {
       callback(_response)
    })
}