簡體   English   中英

如何在Node.js中按順序發送許多http請求?

[英]How to send many http request by sequentially in Node.js?

我正在使用Node.js創建搜尋器。

在目標網頁中,有10多個類別。

我可以使用我的搜尋器來獲取它們。

我針對每個類別提出要求。 (超過10個要求)

然后,每個類別頁面有100多個項目。

我要求每個項目。 (超過100個要求)

所以我需要10+ * 100+個請求!

我的代碼在這里。

const axios = require("axios")
const cheerio = require("cheerio");

async function request(url) {
    return await axios.get(url);
}

function main() {
    request(url).then(html => {
        const $ = cheerio.load(html.data);
        const categoryArray = $('table.table tbody').children('tr').toArray()

        categoryArray.map(category => {
            console.log("category: " + category.name)

            request(category.url).then( html => {
                const $ = cheerio.load(html.data);
                const items = $('table.table tbody').children('tr').toArray()

                console.log("item.length: " + items.length)

                items.map(item => {
                    request(item).then(html => {
                        const $ = cheerio.load(html.data);
                        const itemDetails = $('table.table tbody').children('tr').toArray()

                        console.log("item.name: " + itemDetails.name)
                    })
                })
            })
        })
    })
}

但這行不通...

console.log看起來像:

category: A
category: B
category: C
category: D
category: E
category: F
category: G
category: H
category: I
category: J
category: K
category: L
category: M
category: N
item.length: 0
item.length: 100
item.length: 100
item.length: 0
item.length: 100
item.length: 0
item.length: 0
item.length: 100
item.length: 0
item.length: 0
item.length: 0
item.length: 0
item.length: 0
item.length: 0
item.name: item1
(node:5409) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:5409) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

第一次時,看起來工作正常,但是幾秒鍾后,它不起作用。

我認為“ categoryArray.map”不會等待孩子的請求。

因此,HTTP連接線程數最大。

我不知道該如何解決...

您的問題是Array.prototype.map不了解Promise ,因此它無法等待您的請求。

無需使用map ,只需使用async / await並使用for ... of迭代數組:

async function main() {
    const categoryArray = await request(categoryUrl)
    for (const category of categoryArray) {
        console.log("category: " + category.name)

        const items = await request(category.url)
        console.log("item.length: " + items.length)

        for (const item of items) {
            const itemDetails = await request(item)
            console.log("item.name: " + itemDetails.name)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM