【问题标题】:How to deal with multiple async calls in the Wikipedia API如何处理 Wikipedia API 中的多个异步调用
【发布时间】:2020-12-05 02:05:58
【问题描述】:

我想查找维基百科页面上包含的所有链接,但是如何绕过异步执行?

以下代码获取页面链接列表。我能做到的。问题是如果我需要获取第二页链接(每个请求 500 个链接),我不知道如何让它按顺序运行。 我按顺序需要它的原因是我将它包装在一个获取“所有”链接的函数周围。我不确定这是否是一种好的做法。

function findLinksInPage(parent, plcontinue) {
    var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=links&titles=' + parent + '&pllimit=500'
    if(plcontinue != undefined) {
        url += '&plcontinue=' + plcontinue
    }

    var links = []
    var plcontinue
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if(data.continue != undefined) {
                plcontinue = data.continue.plcontinue
            }
            for(key in data.query.pages) {
                const linksPart = data.query.pages[pageId].links
                linksPart.forEach( value => {
                    const link = value.title
                    // console.log('Link found: ' + link)
                    links.push(link)
                })
                var nextLinks = findLinksInPage(parent, plcontinue)
                links.concat(nextLinks)
                return links
            }
        })

        .catch(error => {
            console.log(console.error(error))
        })
}

【问题讨论】:

  • 为什么是“.catch”?和之前的空行(例如,隐式semicolon problems)?它应该工作吗?

标签: javascript asynchronous mediawiki wikipedia


【解决方案1】:

如果您不限于某些浏览器版本,我建议使用async/await 语法以使其更清晰:

async function findLinksInPage(parent, plcontinue) {
    var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=links&titles=' + parent + '&pllimit=500'
    if(plcontinue != undefined) {
        url += '&plcontinue=' + plcontinue
    }

    var links = []
    var plcontinue

    try {
        let response = await fetch(url);
        let data = await response.json()

        if(data.continue != undefined) {
            plcontinue = data.continue.plcontinue
        }

        for(key in data.query.pages) {
            const linksPart = data.query.pages[pageId].links
            linksPart.forEach( value => {
                const link = value.title
                // console.log('Link found: ' + link)
                links.push(link)
            })
            var nextLinks = await findLinksInPage(parent, plcontinue)
            links.concat(nextLinks)
        }
        return links // <- not inside for
    }
    catch(error) {
        console.error(error)
    }
}

函数findLinksInPage 是一个promise,所以在第一个调用中你可以添加一个findLinksInPage(parent, plcontinue).then(allLinks=&gt; console.log(allLinks)) 调用。

【讨论】:

  • 为什么是单独的分号?
  • @PeterMortensen ?
猜你喜欢
  • 2018-08-05
  • 2021-08-28
  • 1970-01-01
  • 2011-03-18
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2021-06-18
相关资源
最近更新 更多