繁体   English   中英

如何使用 axios.all 捕获所有承诺?

[英]How to catch all promises with axios.all?

我正在使用axioscheerio抓取网页:
这个网页有很多链接,向下滚动时加载更多(比如facebook )。
我想向下滚动时抓取每个链接直到到达结尾。
这是我的代码示例:

cheerio = require('cheerio')
axios = require('axios')

function getLink(id) {
    return axios(options).then(function(response) {
        // Do stuff...
    })
}

function scrollDown() {
    axios(scrollOptions).then(function(response) {
        $ = cheerio.load(response['data'])
        isScrollFinished = ($('.page_more').length == 0)
        promises = []
        newLinks = $('.link') // Get the new links that were loaded while scrolling
        newLinks.each(function() {
            promises.push(getLink($(this).attr('id')))
        })
        axios.all(promises).then(responseArr => {
            if(isScrollFinished) {
                // Exit script
            }
        })
        if(!isScrollFinished) {
            scrollDown()
        }
    })
}

scrollDown()

这段代码的问题在于,有时在我退出之前它不会抓取所有链接。
这是因为最后一个 axios.all 只会等到最后一个滚动页面的所有链接都被刮掉。
我该如何解决?

我将 promises 数组创建为静态变量,并且仅在滚动结束时对其调用 axios.all:

cheerio = require('cheerio')
axios = require('axios')

function getLink(id) {
    return axios(options).then(function(response) {
        // Do stuff...
    })
}

function scrollDown() {
    if (typeof scrollDown.promises === 'undefined') { 
        scrollDown.promises = [] // Define static variable if undefined
    }
    axios(scrollOptions).then(function(response) {
        $ = cheerio.load(response['data'])
        isScrollFinished = ($('.page_more').length == 0)
        newLinks = $('.link') // Get the new links that were loaded while scrolling
        newLinks.each(function() {
            scrollDown.promises.push(getLink($(this).attr('id')))
        })
        if(isScrollFinished) {
            axios.all(scrollDown.promises).then(responseArr => {
                // Exit script
            })
        }
        else {
            scrollDown()
        }
    })
}

scrollDown()

更好的解决方案将很乐意被接受。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM