gpt4 book ai didi

javascript - Promise.all() 在完成之前停止工作

转载 作者:行者123 更新时间:2023-12-02 21:17:50 25 4
gpt4 key购买 nike

我有一个非常简单的脚本,它通过映射大约 150 条记录的数组来获取一些信息,代码似乎可以很好地处理较少数量的记录,但每次我用这 150 条记录运行它时,它就会停止工作,并且没有继续,我认为这可能是 Promise.all 问题。

有什么想法吗?

代码:

const request = require('request');
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs').promises;

let champions = [];

const getChampData = async hrefs => {
const requests = hrefs.map(async ({ href }) => {
try {
const html = await axios.get(href);
const $ = cheerio.load(html.data);

const champName = $('.style__Title-sc-14gxj1e-3 span').text();

let skins = [];

$('.style__CarouselItemText-sc-1tlyqoa-16').each((_, el) => {
const skinName = $(el).text();
skins.push(skinName);
});

const champion = {
champName,
skins
};
console.log(champion);

return champion;
} catch (err) {
console.error(err);
}
});

const results = await Promise.all(requests);

await fs.writeFile('json/champions-skins.json', JSON.stringify(results));
return results;
};

编辑#1:

我使用了一个名为 p-map 的包,现在一切正常!

const axios = require('axios');
const pMap = require('p-map');
const cheerio = require('cheerio');
const fs = require('fs').promises;

const getChampData = async hrefs => {
// const champions = JSON.parse(await fs.readFile('json/champions.json'));

try {
let champsList = await pMap(hrefs, async ({ href }) => {
const { data } = await axios(href);

const $ = cheerio.load(data);

const champName = $('.style__Title-sc-14gxj1e-3 span').text();

let skins = [];

$('.style__CarouselItemText-sc-1tlyqoa-16').each((_, el) => {
const skinName = $(el).text();
skins.push(skinName);
});

const champion = {
champName,
skins
};

console.log(champion);

return champion;
});
await fs.writeFile(
'champions-with-skins-list.json',
JSON.stringify(champsList)
);
} catch (err) {
console.error(err.message);
}
};

最佳答案

错误返回丢失。看起来像是某些要获取的网址存在问题。

const getChampData = async hrefs => {
const requests = hrefs.map(async ({ href }) => {
try {
const html = await axios.get(href);
// rest of the code
} catch (err) {
console.error(err);
return []
}
});

const results = await Promise.all(requests);

await fs.writeFile("json/champions-skins.json", JSON.stringify(results));
return results;
};

关于javascript - Promise.all() 在完成之前停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60920065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com