You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Promise.all并行抓取数据返回顺序随机,有什么简单排序方法?

问题解决方法

你出现顺序错乱的核心原因是:在每个请求的then回调里直接往newProducts数组push数据,哪个请求先返回就先执行push操作,最终顺序自然和原始URL顺序不一致。

而Promise.all本身就内置了顺序保证:它返回的结果数组的顺序,和你传入的Promise数组的顺序完全一致,和各个Promise的完成先后没有关系,利用这个特性就能轻松解决问题,无需额外复杂逻辑,还能保留并行请求的全部性能优势。

修改后的代码示例如下:

const pageSrcs = [];

for (let i = 1; i < 26; i++) {
  let pageSrc = $(
    `#product_listing > tbody > #_${i} > td:nth-child(2) > a`
  ).attr("href");

  pageSrc = "https://www.supplier.co.uk" + pageSrc;
  pageSrcs.push(pageSrc);
}

// 直接接收Promise.all的返回值,顺序和pageSrcs完全对应
const newProducts = await Promise.all(
  pageSrcs.map((pageSrc) =>
    fetch(pageSrc)
      .then((res) => res.text())
      .then((html2) => {
        const $2 = cheerio.load(html2);

        let imageSrc = $2(
          "#product-main-image .main-image-inner:first-child img"
        ).attr("src");
        const name = $2("#product-details dd:nth-child(2)").text();
        const brand = $2("#product-details dd:nth-child(4)").text();
        const price = $2("#product-details dd:nth-child(6)").text();
        // 补充你自己的其余字段解析逻辑
        const stock = ""
        const arrival = ""
        const type = ""
        
        // 直接返回当前产品对象,不要在这里手动push
        return {
          name,
          imageSrc,
          brand,
          price,
          pageSrc,
          stock,
          arrival,
          type,
        };
      })
  )
);

return newProducts;

内容的提问来源于stack exchange,提问作者Liiaam93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:27:01