【问题标题】:How to catch all promises with axios.all?如何使用 axios.all 捕获所有承诺?
【发布时间】:2020-07-13 21:46:04
【问题描述】:

我正在使用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 只等到 last 滚动页面的所有链接都被抓取。
我该如何解决这个问题?

【问题讨论】:

  • // Do Stuff 表示模棱两可。是故意不显示实现代码,还是实际上是它本身
  • 故意不显示代码的实现,与问题无关

标签: node.js promise axios


【解决方案1】:

我将 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()

我们很乐意接受更好的解决方案。

【讨论】:

    猜你喜欢
    • 2018-07-18
    • 2021-11-06
    • 2017-11-24
    • 2015-10-06
    • 2017-08-02
    • 2021-11-15
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多