gpt4 book ai didi

javascript - 在 JavaScript 中重构异步函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:21 25 4
gpt4 key购买 nike

我编写了一个程序,分三步提取下载照片的链接:

  1. getPersons() 函数获取要遍历的完整人员列表。
  2. 从人员列表中获取照片下载链接。
  3. 从第 2 步中创建的列表中下载。

我正在尝试将步骤 2 重构为异步函数。有没有一种简单的方法可以将第二步重构为函数以使代码更具可读性?

理想情况下,我想检索所有链接,然后才开始下载。

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

const url = "https://www.website.com";

const persons = [];

async function getPersons() {
await axios.get(url).then(response => {
const html = response.data;
const $ = cheerio.load(html);
const personList = $(".bio-btn");
console.log(personList.length);

personList.each(function() {
const link_raw = $(this).attr("href");

const link = url + link_raw;
const name = link_raw.replace("/bio/", "");

person.push({
name,
link
});
});
});
}

getPersons().then(function() {
persons.forEach(async function(person) {
var personLink = person.link;
await axios.get(personLink).then(response => {
const html = response.data;
const $ = cheerio.load(html);
const snapshots = $(".ratio-4-3");
snapshots.each(function() {
const pic = $(this).attr("style");
if (pic != undefined && pic.includes("biopicture")) {
var bioPhoto = s[1];
}
});
});
});
});

最佳答案

您几乎无法从异步性中获得太多好处,因为您最终会发出串行请求。我会这样写(未经测试):

async function getPersons() {
const response = await axios.get(url);
const html = response.data;
const $ = cheerio.load(html);
const personList = $('.bio-btn');

const persons = [];
personList.each(function() {
const link_raw = $(this).attr('href');

const link = url + link_raw;
const name = link_raw.replace("/bio/", "");

persons.push({
name,
link,
});
});
return persons;
};

async function getSnapshots() {
const persons = await getPersons();
const linkPromises = persons.map(person => axios.get(person.link));
const linkResponses = await Promise.all(linkPromises);
linkResults.forEach(response => {
const html = response.data;
const $ = cheerio.load(html);
const snapshots = $(".ratio-4-3");
// ...
});
}

关于javascript - 在 JavaScript 中重构异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58974464/

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