为了账号安全,请及时绑定邮箱和手机立即绑定

在 javascript 中重构异步函数

在 javascript 中重构异步函数

POPMUISE 2022-01-07 10:37:27
我编写了一个程序来提取链接以通过三个步骤下载照片:getPersons() 函数获取要遍历的人员的完整列表。从人员列表中获取照片下载链接。从步骤 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];        }      });    });  });});
查看完整描述

2 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

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


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");

    // ...

  });

}


查看完整回答
反对 回复 2022-01-07
?
富国沪深

TA贡献1790条经验 获得超9个赞

我会像这样重构它。删除匿名函数上的.then()方法和function关键字使代码看起来更干净。

使用Promise.all()使您可以异步启动所有下载,这可能比一张一张下载图像更好。


const axios = require('axios');

const cheerio = require('cheerio');


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



async function getPersons() {

  const response = await axios.get(url);

  return extractPersonList(response);

}


// Step 1

function extractPersonList(response) {

  const persons = [];

  const html = response.data;

  const $ = cheerio.load(html);

  const personList = $('.bio-btn');

  console.log(personList.length);

  personList.each(() => {

    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 getPhotos() {

  const persons = await getPersons();

  const promisies = persons.map(p => axios.get(p.link));

  // Step 2

  const responses = await Promise.all(promisies);


  // Step 3

  responses.forEach(response => {

    const html = response.data;

    const $ = cheerio.load(html);

    const snapshots = $('.ratio-4-3');

    snapshots.each(() => {

      const pic = $(this).attr('style');

      if (pic && pic.includes('biopicture')) {

        var bioPhoto = s[1];

      }

    });

  });

}


// Call getPhotos to start the process

getPhotos();


查看完整回答
反对 回复 2022-01-07
  • 2 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号